Borrar filtros
Borrar filtros

File .txt in MatLab

3 visualizaciones (últimos 30 días)
Francesco
Francesco el 18 de Oct. de 2011
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

Respuestas (2)

Thomas
Thomas el 18 de Oct. de 2011
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

Laura Proctor
Laura Proctor el 18 de Oct. de 2011
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.

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by