Having trouble using cell2mat

2 次查看(过去 30 天)
Francisco Michel
Francisco Michel 2019-9-11
编辑: Adam Danz 2019-9-13
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 个评论
dpb
dpb 2019-9-11
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)

请先登录,再进行评论。

回答(1 个)

Adam Danz
Adam Danz 2019-9-11
编辑:Adam Danz 2019-9-13
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.

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by