Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Matlab textscan

I'm working with transferring some Matlab code to Python. I'm relatively new to Python and am unsure of a Python equivalent of Matlab's textscan method. Any help would be greatly appreciated.

like image 299
shadonar Avatar asked Oct 29 '12 16:10

shadonar


3 Answers

If you're translating Matlab to Python, I'll assume you're already using NumPy.

In that case, you can use np.loadtxt (if no values are missing) or np.genfromtxt (if there are missing values: I'm not sure whether Matlab's textscan handles that).

Give us a few more details if you need more help!

like image 121
jorgeca Avatar answered Sep 19 '22 08:09

jorgeca


Example of conversion of MATLAB's textscan to Python + NumPy's np.loadtxt:

Let our data file results.csv contain:

0.6236,sym2,1,5,10,10
0.6044,sym2,2,5,10,10
0.548,sym2,3,5,10,10
0.6238,sym2,4,5,10,10
0.6411,sym2,5,5,10,10
0.7105,sym2,6,5,10,10
0.6942,sym2,7,5,10,10
0.6625,sym2,8,5,10,10
0.6531,sym2,9,5,10,10

Matlab code:

fileID = fopen('results.csv');
d = textscan(fileID,'%f %s %d %d %d %d', 'delimiter',',');
fclose(fileID);

Python + NumPy code:

fd = open('results2.csv','r')    
d = np.loadtxt(fd,
           delimiter=',',
           dtype={'names': ('col1', 'col2', 'col3', 'col4', 'col5', 'col6'),
           'formats': ('float', 'S4', 'i4', 'i4', 'i4', 'i4')})
fd.close()

For more info on types, see Data type objects (dtype).

like image 22
Franck Dernoncourt Avatar answered Sep 18 '22 08:09

Franck Dernoncourt


you have to look for Numpy and py2mat. If my understanding of textscan() is correct you could just use open()

like image 26
f.ashouri Avatar answered Sep 21 '22 08:09

f.ashouri