Having trouble using cell2mat

5 Ansichten (letzte 30 Tage)
Francisco Michel
Francisco Michel am 11 Sep. 2019
Bearbeitet: Adam Danz am 13 Sep. 2019
I need to read a txt file for a class and I can read the file and can extract the information that I need from the file but when I try to convert from a cell array to matrix in order to do mathematical operations on it gives me a error here is the code and the error message
fid=fopen('SR4.txt','r');
filedata=textscan(fid,'%s%s','Delimiter','\t','headerlines',1);
x=filedata{1,1};
X=x(3:end);
y=filedata{1,2};
Y_cell=y(3:end);
Y_Matrix=cell2mat(Y_cell);
fclose(fid);
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
Error in ME190lab (line 7)
Y_Matrix=cell2mat(Y_cell);
  1 Kommentar
dpb
dpb am 11 Sep. 2019
fid=fopen('SR4.txt','r');
filedata=textscan(fid,'%s%s','Delimiter','\t','headerlines',1)
...
But, your file has three header lines, not just 1 before you get to numeric data.
So, why not read the numeric data directly as numeric instead of strings to convert later?
If you want the header info, unless your assignment requires textscan, why not use readtable instead which can handle the header line and the variableunits line as well (with a little help with detectimportoptions)

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adam Danz
Adam Danz am 11 Sep. 2019
Bearbeitet: Adam Danz am 13 Sep. 2019
You were on the right track. You're reading the data as cell array of strings so you need to convert the data to numeric using str2double.
fid=fopen('SR4.txt','r');
filedata=textscan(fid,'%s%s','Delimiter','\t','headerlines',1);
fclose(fid);
m = str2double([filedata{1}(3:end), filedata{2}(3:end)]);
*Avoid the (3:end) indexing by correctly indicating the number of headers (3) as dpb pointed out in his comment.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by