如何在Matlab中按列读取此文件(具有重复模式)?
该文件是一个输出文件,其第一行是一个标题,后面是带有数据的如何在Matlab中按列读取此文件(具有重复模式)?,matlab,design-patterns,file-io,text-files,Matlab,Design Patterns,File Io,Text Files,该文件是一个输出文件,其第一行是一个标题,后面是带有数据的n行。第一组数据之后是具有不同值的更相似的数据集 我想从该文件中读取所有数据集的第2列和第3列,即方向1,方向2,等等。目前,我正在函数中使用以下代码行读取数据,如下所示: fid = fopen(output_file); % open the output file dotOUT_fileContents = textscan(fid,'%s','Delimiter','\n'); % read it as string ('%s'
n
行。第一组数据之后是具有不同值的更相似的数据集
我想从该文件中读取所有数据集的第2列和第3列,即方向1
,方向2
,等等。目前,我正在函数中使用以下代码行读取数据,如下所示:
fid = fopen(output_file); % open the output file
dotOUT_fileContents = textscan(fid,'%s','Delimiter','\n'); % read it as string ('%s') into one big array, row by row
dotOUT_fileContents = dotOUT_fileContents{1};
fclose(fid); %# close the file
%# find rows containing 'SV'
data_starts = strmatch('SV',...
dotOUT_fileContents); % data_starts contains the line numbers wherever 'str2match' is found
nDataRows=data_starts(2)-data_starts(1)-1;
ndata = length(data_starts); % total no. of data values will be equal to the corresponding no. of 'str2match' read from the .out file
%# loop through the file and read the numeric data
for w = 1:ndata
%# read lines containing numbers
tmp_str = dotOUT_fileContents(data_starts(w)+1:data_starts(w)+nDataRows);
%# convert strings to numbers
y = cell2mat(cellfun(@(z) sscanf(z,'%f'),tmp_str,'UniformOutput',false)); % store the content of the string which contains data in form of a character
data_matrix_column_wise(:,w) = y; % convert the part of the character containing data into number
%# assign output in terms of lag and variogram values
lag_column_wise(:,w)=data_matrix_column_wise(2:6:nLag*6-4,w);
vgs_column_wise(:,w)=data_matrix_column_wise(3:6:nLag*6-3,w);
end
如果我没有在上面的输出文件中显示星星,那么这个函数工作得很好。但是,上面显示的输出文件中有一个包含星号,在这种情况下,上面的代码失败了。应该如何处理数据中的星星,以便我能够正确读取第2列和第3列 问题在于代码的这一部分:
sscanf(z,'%f')
您强制匹配一个浮点数,当它遇到星号时失败。你最好用类似的东西来代替它
textscan(z, '%f %f %f %s %f %f', 'Delimiter', '\t')
移除cell2mat并适当修改以下行,以测试是否存在字符串
或者,这取决于这些星号的含义,您可以用零或有意义的东西替换这些星号,您当前的代码就可以正常工作。问题在于代码的这一部分:
sscanf(z,'%f')
您强制匹配一个浮点数,当它遇到星号时失败。你最好用类似的东西来代替它
textscan(z, '%f %f %f %s %f %f', 'Delimiter', '\t')
移除cell2mat并适当修改以下行,以测试是否存在字符串
或者,这取决于这些星号的含义,您可以用零或有意义的东西替换这些星号,您当前的代码就可以正常工作了。将所有列作为字符串读取,并使用:
C = textscan(fid, '%s%s%s%s%s%s');
这将为您提供一个C,它是一个包含6列的单元格数组。您可以通过以下方式访问C的元素:
列n和行m的C{1,n}{m}。
然后在for循环中,你可以从48中减去这些值,得到这样的数字
for n=1:6
for m=1:M
A(m,n) = C{1,n}{m}-48;
end
end
你所需要的将存储在矩阵A中。当然,你可以将C{1,n}{m}与这8颗星进行比较,然后决定你想用它做什么 以字符串形式读取所有列,并使用:
C = textscan(fid, '%s%s%s%s%s%s');
这将为您提供一个C,它是一个包含6列的单元格数组。您可以通过以下方式访问C的元素:
列n和行m的C{1,n}{m}。
然后在for循环中,你可以从48中减去这些值,得到这样的数字
for n=1:6
for m=1:M
A(m,n) = C{1,n}{m}-48;
end
end
你所需要的将存储在矩阵A中。当然,你可以将C{1,n}{m}与这8颗星进行比较,然后决定你想用它做什么