我想写一个matlab函数,将数据加载到矩阵中。问题是数据每行都有一个更多的值。所以我不能使用负载,所以我试图使用fgetl。在matlab中读取dat文件到不同数量的数据每行不同
的数据是这样的:
143234
454323 354654
543223 343223 325465
等
我所做的是创建零矩阵,尺寸是高度和数据的最长的字符串。为了将数据放入矩阵中,我使用fgetl来读取每一行,然后使用textscan将数据以空格分隔。然后我用str2num(我认为这是错误的地方)将字符串转换为数字。
第一继承人我的代码:
%READTRI Opens the triangle dat file and turns it into a matrix
fid = fopen('triangledata.dat');
%create matrix of zeros for the data to be retrieved
trimat = zeros(15,15);
%Check to see if the file loaded properly
if fid == -1
disp('File load error')
else
%if it does, continue
%read each line of data into a
while feof(fid) == 0
%run through line by line
aline = fgetl(fid);
%split aline into parts by whitespace
splitstr = textscan(aline,'%s','delimiter',' ');
%This determines what row of the matrix the for loop writes to
rowCount = 1;
%run through cell array to get the numbers out and write them to
%the matrix
for i = 1:length(splitstr)
%convert to number
num = str2num(splitstr{i});
%write num to matrix
trimat(rowCount, i) = num;
end
%iterate rowCount
rowCount = rowCount + 1;
end
%close the file
closeresult = fclose(fid);
%check for errors
if closeresult == 0
disp('File close successful')
else
disp('File close not successful')
end
end
end
我得到的错误是:
Error using str2num (line 33)
Requires string or character array input.
Error in readTri (line 32)
num = str2num(splitstr{i});
让我困扰的是,当我尝试,在互动控制台的同一件事,那张在循环即import aline中,使用textscan将其拆分为单元数组,然后使用num2str将其转换为整数。一切正常。所以无论我使用num2str的方式是错误的还是for循环做了一些有趣的事情。
我只是希望有想法,有很多数据,所以加载零使负载工作是不可能的。
感谢您的阅读!
哇。这节省了大量的空间,非常感谢! – waywardEevee