File .txt in MatLab
1 次查看(过去 30 天)
显示 更早的评论
Hi guys,
I have a little problem in opening a file.txt in MatLab: the file contains a matrix structured with strings and numbers. I give you an exemple: let's say the file contains the following matrix 3x3
AAB 11 23
CC 5 40
DEF 54 4
I'd like to create a matrix "A" such that A(1,1) = AAB. To do this i use the command
test=fopen('filename.txt','r')
to import the file, and then
A=fscanf(test,'%s',[3,3])
to open the file, but this give me a problem: it doesn't return a 3x3 matrix.
How can i solve this problem? Thanks in advance
0 个评论
回答(2 个)
Thomas
2011-10-18
If my data is in the file new.txt
fid=fopen('new.txt');
C = textscan(fid, '%s %s %f32 %d8 %u %f %f %s %f');
fclose(fid);
C{1} % will give you the first column
>>C{1} ans = 'AB' 'CC' 'DEF'
C{2} % will give you the second column
>> C{2} ans = '11' '5' '54'
C{3} % will give you the third column
>> C{3}
ans =
23.00
40.00
4.00
Also you can always convert the data from cell to string or to num as you wish with the cell2mat, str2num etc commands..
Hope this helps
0 个评论
Laura Proctor
2011-10-18
The following code will create a cell array that does what you like. Since you have mixed data types in the file, a cell array is going to be your best bet for importing everything into one variable.
fid = fopen('test.txt','r');
A = textscan(fid,'%s %u %u','delimiter',' ');
fclose(fid);
A = [ A{:,1} num2cell(A{:,2}) num2cell(A{:,3}) ];
Note that if you want to get out the contents from the first cell, you must use the syntax A{1,1} rather than A(1,1). Type them both in and see the difference in the class type in the Workspace.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!