Having trouble using cell2mat
2 ビュー (過去 30 日間)
古いコメントを表示
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
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
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!