0

Saving and loading using scipy.io.savemat and scipy.io.loadmat does not distinguish between a 1D numpy array and a 2D numpy array with one length 1 dimension.

In the example below, how can I get a1 to have the same shape as a, and b1 to have the same shape as b?

    import numpy as np
    from scipy import io

    a = np.array([1,2,3])
    b = np.array([[1],[2],[3]])
    c = np.array([[1,10],[2,20],[3,30]])

    print(f'a: {a.shape}')
    print(f'b: {b.shape}')
    print(f'c: {c.shape}')

    io.savemat('test.mat', {'a': a, 'b': b, 'c': c}, appendmat = False, oned_as='row')
    ##################################################################################
    loadedData = io.loadmat('test.mat', appendmat = False, squeeze_me = False)
    a1 = loadedData['a']
    b1 = loadedData['b']
    c1 = loadedData['c']
    print(f'a1: {a1.shape}')
    print(f'b1: {b1.shape}')
    print(f'c1: {c1.shape}')

Desired Result:

    a: (3,)
    b: (3, 1)
    c: (3, 2)
    a1: (3,)
    b1: (3, 1)
    c1: (3, 2)

Actual Result:

    a: (3,)
    b: (3, 1)
    c: (3, 2)
    a1: (1, 3)
    b1: (3, 1)
    c1: (3, 2)

What doesn't work?

I've tried all permutations of the "oned_as", "squeeze_me", "struct_as_record", and "matlab_compatible" parameters. Changing "oned_as" switches a1 between (1, 3) and (3, 1). Turning "squeeze_me" on fixes a1, but causes b1 to have shape (3,).

Selvek
  • 130
  • 1
  • 9
  • `savemat` has to create MATLAB compatible files. There everything is 2d (or more) – hpaulj Feb 09 '21 at 00:11
  • Since `savemat` creates a MATLAB compatible variables, so `a` has to be either (3,1) or (1,3) as you found. The `loadmat` can't distinguish between a size 1 dimension that you started with and one that `savemat` created. Use `np.save/load` if you don't want any of these changes. – hpaulj Feb 09 '21 at 01:19

0 Answers0