Reputation: 863
I am trying to pass a matrix variable from MATLAB to python, but I am only acquiring the first element of that matrix in python. Does anyone know can get the full matrix?
Python
import sys
if __name__ == '__main__':
x = sys.argv[1]
print x
MATLAB
A = magic(5);
[str,err] = sprintf('/usr/local/python name_of_program.py %d ', A);
unix(str)
Upvotes: 3
Views: 974
Reputation: 12983
You might want to use numpy to reshape the array, too. Or if it's too much to import, you could make your own reshape function Try this:
import sys, numpy
if __name__ == '__main__':
x = sys.argv[1::3]
y = numpy.reshape(x, (5,5))
print y
I also notice that the call is adding the string once for each element of A, so you might consider using mat2str(A), like:
[str, err] = sprintf('/usr/local/python program.py "%s" ', mat2str(A));
I've also changed the %d to %s, because you're passing it as a string on the python anyway. The output of this is:
python program.py "[17 24 1 8 15;23 5 7 14 16;4 6 13 20 22;10 12 19 21 3;11 18 25 2 9]"
You can make a matrix from that string with numpy as well
>>> import sys
>>> import numpy
>>> print(numpy.matrix(sys.argv[1]))
matrix([[17, 24, 1, 8, 15],
[23, 5, 7, 14, 16],
[ 4, 6, 13, 20, 22],
[10, 12, 19, 21, 3],
[11, 18, 25, 2, 9]])
Upvotes: 0
Reputation: 1022
Look at the contents of str: /usr/local/python name_of_program.py 17 /usr/local/python name_of_program.py 23 /usr/local/python name_of_program.py 4 ...
When you pass a 5x5 matrix to sprintf, it reproduce the formatting string 25 times, with one of the elements substituted for the %d, in order (column by column).
I suggest another way to transfer data between the programs, such as writing it to a file. If you really want to pass everything on the command line, try the following:
A_str = sprintf(' %d',A);
str = strcat('/usr/local/python name_of_program.py ',A_str);
Upvotes: 1