1

该文件是一个输出文件,其第一行是标题,后跟n数据行。第一组数据之后是具有不同值的更相似的数据组。

我想从该文件中读取所有数据集的第 2 列和第 3 列,即direction 1,direction 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 列?

4

2 回答 2

3

问题是您的代码的这一部分:

sscanf(z,'%f')

你强制匹配一个浮点数,当它遇到星星时它会失败。你最好用类似的东西代替它

textscan(z, '%f %f %f %s %f %f', 'Delimiter', '\t')

并删除 cell2mat 并适当修改以下行以测试是否存在字符串。

或者,这取决于这些星星的含义,您可以将星星替换为零或有意义的东西,您当前的代码就可以正常工作。

于 2012-07-12T17:54:45.127 回答
1

将所有列作为字符串读取:

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 颗星进行比较,然后决定您想用它做什么。

于 2012-07-13T00:28:45.920 回答