编辑
我已经更新了代码,以便您更好地理解该过程:
% An empty array:
importedarray = [];
% Open the data file to read from it:
fid = fopen( 'dummydata.txt', 'r' );
% Check that fid is not -1 (error openning the file).
% read each line of the data in a cell array:
cac = textscan( fid, '%s', 'Delimiter', '\n' );
% size(cac{1},1) must equals the # of rows in your data file.
totalRows = size(cac{1},1);
fprintf('Imported %d rows of data!\n',totalRows)
% Close the file as we don't need it anymore:
fclose( fid );
% for total rows in data
for k=1:totalRows
fprintf('Parsing data on row %d of %d...\n',k,totalRows);
currentRow = cac{1}{k,1};
fprintf('Row contains:\n%s\n',currentRow);
% finish (break from loop) when encounter an empty row:
if isempty(currentRow)
fprintf('Empty row encountered (#%d). Exiting the loop...\n',k);
break;
end
eachRowElement = strsplit(currentRow, ' ');
fprintf('Splitting row to %d elements...\n',length(eachRowElement));
fprintf('Converting row to floats...');
eachRowElement2num = cellfun(@str2num,eachRowElement,'UniformOutput',false);
fprintf('Done!\n');
fprintf('Converting cell to matrix...');
importedarray(k,:) = cell2mat(eachRowElement2num);
fprintf('Done!\n');
end
clearvars cac k fid totalRows currentRow eachRowElement eachRowElement2num;
鉴于您的示例图像(每行的所有列都填充有浮点数,并且在您停止的空行上),这应该可以完成提供信息的工作。如果不是,您将能够通过查看代码停止的行来判断问题所在。我包含代码以在导入后消除不必要的变量。这必须手动完成,或者您可以创建一个函数来执行任务(函数的工作空间不同,临时变量在函数返回时被删除,请参阅:http://www.mathworks.com/help/matlab/ref/function.html)。希望这会有所帮助。
PS。在您的示例中,您保留 12 列跳过前两列。上面的代码将导入整行。您可以使用矩阵索引来选择以后要保留的列,例如:
importedarray = 导入数组(:,3:14);
如果这些列没有改变,您可以将其合并到您的函数中。