Python to Mat-file: export list of string to ordinar matrix of chars (not a cell-array!)
This code on Python creates cell "STRINGS" in .mat-file:
data = {"STRINGS": numpy.empty((0),dtype=numpy.object)}
data["STRINGS"] = numpy.append( data["STRINGS"], "Some string" )
scipy.io.savemat( output_mat_file, data )
In matlab I get cell STRINGS:
>> STRINGS{1}
ans =
Some string
How could I get ordinary matrix? For instance:
>> strings(1,:) = char('Some ');
>> strings(1,:)
开发者_运维百科
ans =
Some
EDIT
If I run following code, I'll get misunderstood array mangling.
Python:
list = ['hello', 'world!!!']
scipy.io.savemat(output_mat_file, mdict={'list':list})
Matlab:
>> list
list =
hlo wrd!
In MATLAB, cell arrays are containers for heterogeneous data types, while matrices are not, and all their elements must be of the same type (be it numeric doubles or characters)
Matrices are of rectangular shapes (thus if you store strings in each 2D matrix row, they all must be of the same length, or padded with spaces). This notion applies to multi-dimensional matrices as well.
The MATLAB equivalent of Python's lists are cell arrays:
Python
x = [1, 10.0, 'str']
x[0]
MALTAB
x = {int32(1), 10, 'str'}
x{1}
EDIT:
Here is an example to show the difference:
Python
import numpy
import scipy.io
list = ['hello', 'world!!!']
scipy.io.savemat('file.mat', mdict={'list':list})
list2 = numpy.array(list, dtype=numpy.object)
scipy.io.savemat('file2.mat', mdict={'list2':list2})
MATLAB
>> load file.mat
>> load file2.mat
>> whos list list2
Name Size Bytes Class Attributes
list 2x8 32 char
list2 2x1 146 cell
Now we can access the strings as:
>> list(1,:)
ans =
hello
>> list2{1}
ans =
hello
Note that in the matrix case, the strings were space-padded so that all strings have the same length (you could use STRTRIM)
精彩评论