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!