Having trouble using cell2mat

5 vues (au cours des 30 derniers jours)
Francisco Michel
Francisco Michel le 11 Sep 2019
Modifié(e) : Adam Danz le 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 commentaire
dpb
dpb le 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)

Connectez-vous pour commenter.

Réponses (1)

Adam Danz
Adam Danz le 11 Sep 2019
Modifié(e) : Adam Danz le 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.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by