Having trouble using cell2mat

2 views (last 30 days)
Francisco Michel
Francisco Michel on 11 Sep 2019
Edited: Adam Danz on 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 Comment
dpb
dpb on 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)

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 11 Sep 2019
Edited: Adam Danz on 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.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!