2

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!
Amro
  • 123,847
  • 25
  • 243
  • 454
Mtr
  • 482
  • 5
  • 19

1 Answers1

3

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)

Amro
  • 123,847
  • 25
  • 243
  • 454
  • this page has a good description of data types in MATLAB: http://www.mathworks.com/help/techdoc/matlab_prog/f2-47534.html – Amro Sep 18 '11 at 22:25
  • Thank you. Could you please show me the way to export from Python list of strings to .mat file as matrix? – Mtr Sep 19 '11 at 06:27
  • @Mtr: see my recent edit, I added an example to show how to export as both a matrix of characters and a cell-array of strings – Amro Sep 19 '11 at 17:45
  • I've run your example and the answer was (strings were unclearly mangled): >> list list = hlo wrd! el ol!! – Mtr Sep 19 '11 at 22:49
  • @Mtr: It works just fine for me, I cannot reproduce the results you are showing... For the record, I'm using Python 2.6.6 on WinXP-32, I have numpy 1.6.1 and scipy 0.9.0, and my MATLAB version is R2011a – Amro Sep 20 '11 at 00:24
  • Thank you, I'll dig environment – Mtr Sep 20 '11 at 08:35