我想从Matlab中的文本文件中读取数据。该文件描述了一个由两部分组成的表面: 1)包含x,y尺寸(像素和nm)等信息的标题。 2)具有高度值的矩阵(512x512)
当我尝试首先读取矩阵时,我最终得到的是单个列向量而不是矩阵
C = textscan(id,'%f','HeaderLines',18,'Delimiter','\t')
该文件包含" "分离的值和行分隔矩阵的行。当我手动删除标题并阅读它时,它的工作原理
A=dlmread(path,'\t',[0 0 511 511]);
我想用textscan获得相同的512x512矩阵,这样我以后也可以解析标题 - 我该怎么做?
答案 0 :(得分:1)
如果您未严格遵守textscan
,则可以改为使用fscanf
(请参阅docs)。像这样:
fid = fopen('FileName.txt');
% here you have to skip (or parse) your header lines
% and determine number of rows/columns in your data matrix
A = fscanf(fid, '%g', [NColumns NRows]);
fclose(fid);
% Transpose so that A matches
% the orientation of the file
A = A';
<强> UPDATE1 强>
此代码可能不是很优雅,但它会将您的标头解析为 FileInfo 结构,以便您稍后可以在代码中使用这些数据。
% sample file header
%
% # File Format = ASCII
% # Created by SPIP 6.2.8.0 2014-08-15 20:41
% # Original file: D:\...
% # x-pixels = 512
% # y-pixels = 512
% # x-length = 319375
% # y-length = 319375
% # x-offset = 0
% # y-offset = 0
% # z-unit = [nm]
% # scanspeed = 638.75
% # forcecurve = 0
% # voidpixels =76
% # description =62:Confocal Height Image Date: 2013-08-20T13:36 User: Unknown
% # Start of Data: MATRIX
fid = fopen('text.txt','r');
FileInfo = [];
tmpString = ''; % initializing the s
while isempty(strfind(tmpString,'Start of Data: MATRIX'))
% we read a string from file
tmpString = fgetl(fid);
% and split it into left and right parts according to the '=' position
[kev,val] = strtok( tmpString(3:end) , ':=' );
% remove spaces from key name and make it a valid variable name in MatLab
keyName = genvarname( strrep(strrep(kev,'-',''),' ','') );
% check if key value is a number
[x,OK] = str2num(strtrim(val(2:end)));
% if value is a number, use it otherwise leave the trimmed original string
if OK
FileInfo.(keyName) = x;
else
FileInfo.(keyName) = strtrim(val(2:end));
end
end
% Now we can read the data
A = fscanf(fid, '%g', [FileInfo.xpixels FileInfo.ypixels]);
fclose(fid);
% Transpose so that A matches
% the orientation of the file
%A = A';