way*_*vee 2 file-io matlab matrix
我正在尝试编写一个将数据加载到矩阵中的matlab函数.问题是数据每行有一个值.所以我不能使用加载,所以我试图使用fgetl.
数据看起来像:
143234
454323 354654
543223 343223 325465
Run Code Online (Sandbox Code Playgroud)
等等
我所做的是创建一个零矩阵,维度是高度和最长的数据串.为了将数据放入矩阵,我使用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
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
Error using str2num (line 33)
Requires string or character array input.
Error in readTri (line 32)
num = str2num(splitstr{i});
Run Code Online (Sandbox Code Playgroud)
困扰我的是,当我尝试时,在交互式控制台中,循环中发生的同样的事情,即导入aline,使用textscan将其拆分为单元格数组,然后使用num2str将其转换为整数.一切正常.所以我使用num2str的方式是错误的,或者for循环正在做一些时髦的事情.
我只是希望有想法,有很多数据,所以添加零来使负载工作是不可能的.
谢谢阅读!
您可以使用dlmread而不是load或fgetl只要行长度不够长,它就会自动返回一个带零的矩阵.做就是了
matrix = dlmread('triangledata.dat');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1893 次 |
最近记录: |