该文件是一个输出文件,其第一行是头,后面是带有数据的n行。这第一组数据之后是具有不同值的更相似的数据集。
我想从这个文件中读取所有数据集(如direction 1、direction 2等)的第2和第3列。目前,我在函数中使用以下代码行来读取数据,如下所示:
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?
发布于 2012-07-12 17:54:45
问题在于代码的这一部分:
sscanf(z,'%f')你强迫一个浮点数匹配,当它遇到星星时,它就失败了。你最好用这样的方法来代替
textscan(z, '%f %f %f %s %f %f', 'Delimiter', '\t')并删除cell2mat并适当修改以下行以测试字符串是否存在。
或者,这取决于这些星星的含义,你可以用一个零或者其他有意义的东西来代替星星,你现在的代码会很好。
发布于 2012-07-13 00:28:45
将所有列读入字符串,并使用:
C = textscan(fid, '%s%s%s%s%s%s');这给出了一个C,它是一个包含6列的单元格数组。您可以访问C的元素,如: C{1,n}{ m },用于列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颗星进行比较,并决定你想用它做什么。
https://stackoverflow.com/questions/11456972
复制相似问题