Repository: scipy/scipy

Issue:
BUG: matlab files with deeply lists of arrays with different sizes are no longer created
### Describe your issue.

After updating numpy to a version >=1.24 an error is thrown as the behavior of numpy asanyarry has changed from a deprecation warning to an error. For reference:
https://numpy.org/doc/stable/release/1.24.0-notes.html
and
https://github.com/numpy/numpy/pull/22004

Possible workaround:
Wrapping the line 493 of _mio5.py within a try catch:
https://github.com/scipy/scipy/blob/dde50595862a4f9cede24b5d1c86935c30f1f88a/scipy/io/matlab/_mio5.py#L493
Replace:
```python
narr = np.asanyarray(source)
```
with
```python
try:
    narr = np.asanyarray(source)
except ValueError:
    narr = np.asanyarray(source, dtype=object)
```


### Reproducing Code Example

```python
import scipy.io as sio
import numpy as np

array_one = np.random.random((5,3))
array_two = np.random.random((6,3))

list_of_arrays = [array_one, array_two]

sio.savemat("D:\\lists.mat", {'data': list_of_arrays}, long_field_names=True, do_compression=True)
```


### Error message

```shell
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.3\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 10, in <module>
  File "...\venv310\lib\site-packages\scipy\io\matlab\_mio.py", line 300, in savemat
    MW.put_variables(mdict)
  File "...\venv310\lib\site-packages\scipy\io\matlab\_mio5.py", line 884, in put_variables
    self._matrix_writer.write_top(var, name.encode('latin1'), is_global)
  File "...\venv310\lib\site-packages\scipy\io\matlab\_mio5.py", line 633, in write_top
    self.write(arr)
  File "...\venv310\lib\site-packages\scipy\io\matlab\_mio5.py", line 651, in write
    narr = to_writeable(arr)
  File "...\venv310\lib\site-packages\scipy\io\matlab\_mio5.py", line 493, in to_writeable
    narr = np.asanyarray(source)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
```


### SciPy/NumPy/Python version information

Scipy: 1.10.0; Numpy: 1.24.2


Discussion:
Thanks for the report.  Do you happen to have an example that triggers the error that we can use for a test?
Sorry, I do not understand. What in addition to the example under "Reproducing Code Example" from my initial post is needed?
On my setup this raises the error and aborts writing the mat-file. 

Resolving patch:
diff --git a/scipy/io/matlab/_mio5.py b/scipy/io/matlab/_mio5.py
--- a/scipy/io/matlab/_mio5.py
+++ b/scipy/io/matlab/_mio5.py
@@ -490,7 +490,10 @@ def to_writeable(source):
         else:
             return EmptyStructMarker
     # Next try and convert to an array
-    narr = np.asanyarray(source)
+    try:
+        narr = np.asanyarray(source)
+    except ValueError:
+        narr = np.asanyarray(source, dtype=object)
     if narr.dtype.type in (object, np.object_) and \
        narr.shape == () and narr == source:
         # No interesting conversion possible


Test patch:
diff --git a/scipy/io/matlab/tests/test_mio.py b/scipy/io/matlab/tests/test_mio.py
--- a/scipy/io/matlab/tests/test_mio.py
+++ b/scipy/io/matlab/tests/test_mio.py
@@ -16,7 +16,7 @@
 import gzip
 
 from numpy.testing import (assert_array_equal, assert_array_almost_equal,
-                           assert_equal, assert_, assert_warns)
+                           assert_equal, assert_, assert_warns, assert_allclose)
 import pytest
 from pytest import raises as assert_raises
 
@@ -1299,3 +1299,24 @@ def test_deprecation():
     # These should be importable but warn as well
     with assert_warns(DeprecationWarning):
         from scipy.io.matlab.miobase import MatReadError  # noqa
+
+
+def test_gh_17992(tmp_path):
+    rng = np.random.default_rng(12345)
+    outfile = tmp_path / "lists.mat"
+    array_one = rng.random((5,3))
+    array_two = rng.random((6,3))
+    list_of_arrays = [array_one, array_two]
+    # warning suppression only needed for NumPy < 1.24.0
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(np.VisibleDeprecationWarning)
+        savemat(outfile,
+                {'data': list_of_arrays},
+                long_field_names=True,
+                do_compression=True)
+    # round trip check
+    new_dict = {}
+    loadmat(outfile,
+            new_dict)
+    assert_allclose(new_dict["data"][0][0], array_one)
+    assert_allclose(new_dict["data"][0][1], array_two)