Labview and Matlab for PT

Just a place to discuss with Matlab and Labview

ad

讀取有Header的txt檔

今天我有一個檔案長得如下:



frame force angle
180.000000 25.907727 -96.707100
198.000000 52.657283 -97.686900
206.000000 79.306087 -97.134200
216.000000 105.920720 -96.028800
234.000000 132.531830 -95.501200
252.000000 159.259191 -95.023900
271.000000 185.936060 -94.496300
293.000000 212.583572 -94.194800
312.000000 239.251047 -92.586900
332.000000 265.956685 -91.506600
357.000000 292.655864 -91.556900
364.000000 265.886229 -91.255400
369.000000 239.255744 -91.582000
376.000000 212.594141 -92.813000
384.000000 185.939583 -92.586900
394.000000 159.297355 -93.215000
406.000000 132.574103 -93.390900
421.000000 105.981781 -93.943600
434.000000 79.340140 -94.747500
468.000000 52.674016 -96.104100
501.000000 25.987401 -97.360300



  在matlab裡面一定沒有辦法用既有的textread讀取,因為第一行的文字!於是我寫個個跳過第一行的程式!如下:


function mat_a = get_to_mat(filename,l)
fp = fopen(filename);
current_l = 1;
while 1
content = fgetl(fp);
if current_l <= l
tile = content;
current_l = current_l +1;
elseif current_l > l & ischar(content) == 1
mat_a(current_l - l,:) = str2num(content);
current_l = current_l +1;
elseif ischar(content) == 0
break
end
end
fclose(fp);;



  概念很簡單,就是輸入要跳過的行數,然後以行數來計算一行一行存成矩陣!但是這時候我又想到,剛好今天我這個檔案非常的小,行數也很短,如果我今天拿上萬行的數據執行,執行到死都執行不完!
  百思不得其解後,google了許久,在matlab官方網站看到了有人分享的寫法:



function [header, data] = hdrload(file)


% HDRLOAD Load data from an ASCII file containing a text header.
% [header, data] = HDRLOAD('filename.ext') reads a data file
% called 'filename.ext', which contains a text header. There
% is no default extension; any extensions must be explicitly
% supplied.
%
% The first output, HEADER, is the header information,
% returned as a text array.
% The second output, DATA, is the data matrix. This data
% matrix has the same dimensions as the data in the file, one
% row per line of ASCII data in the file. If the data is not
% regularly spaced (i.e., each line of ASCII data does not
% contain the same number of points), the data is returned as
% a column vector.
%
% Limitations: No line of the text header can begin with
% a number. Only one header and data set will be read,
% and the header must come before the data.
%
% See also LOAD, SAVE, SPCONVERT, FSCANF, FPRINTF, STR2MAT.
% See also the IOFUN directory.


% check number and type of arguments
if nargin < 1
error('Function requires one input argument');
elseif ~isstr(file)
error('Input must be a string representing a filename');
end


% Open the file. If this returns a -1, we did not open the file
% successfully.
fid = fopen(file);
if fid==-1
error('File not found or permission denied');
end


% Initialize loop variables
% We store the number of lines in the header, and the maximum
% length of any one line in the header. These are used later
% in assigning the 'header' output variable.
no_lines = 0;
max_line = 0;


% We also store the number of columns in the data we read. This
% way we can compute the size of the output based on the number
% of columns and the total number of data points.
ncols = 0;


% Finally, we initialize the data to [].
data = [];


% Start processing.
line = fgetl(fid);
if ~isstr(line)
disp('Warning: file contains no header and no data')
end;
[data, ncols, errmsg, nxtindex] = sscanf(line, '%f');


% One slight problem, pointed out by Peter vanderWal: If the
% first character of the line is 'e', then this will scan as
% 0.00e+00. We can trap this case specifically by using the
% 'next index' output: in the case of a stripped 'e' the next
% index is one, indicating zero characters read. See the help
% entry for 'sscanf' for more information on this output
% parameter. We loop through the file one line at a time until
% we find some data. After that point we stop checking for
% header information. This part of the program takes most of the
% processing time, because fgetl is relatively slow (compared to
% fscanf, which we will use later).
while isempty(data)|(nxtindex==1)
no_lines = no_lines+1;
max_line = max([max_line, length(line)]);
% Create unique variable to hold this line of text information.
% Store the last-read line in this variable.
eval(['line', num2str(no_lines), '=line;']);
line = fgetl(fid);
if ~isstr(line)
disp('Warning: file contains no data')
break
end;
[data, ncols, errmsg, nxtindex] = sscanf(line, '%f');
end % while


% Now that we have read in the first line of data, we can skip
% the processing that stores header information, and just read
% in the rest of the data.
data = [data; fscanf(fid, '%f')];
fclose(fid);


% Create header output from line information. The number of lines
% and the maximum line length are stored explicitly, and each
% line is stored in a unique variable using the 'eval' statement
% within the loop. Note that, if we knew a priori that the
% headers were 10 lines or less, we could use the STR2MAT
% function and save some work. First, initialize the header to an
% array of spaces.
header = setstr(' '*ones(no_lines, max_line));
for i = 1:no_lines
varname = ['line' num2str(i)];
% Note that we only assign this line variable to a subset of
% this row of the header array. We thus ensure that the matrix
% sizes in the assignment are equal. We also consider blank
% header lines using the following IF statement.
if eval(['length(' varname ')~=0'])
eval(['header(i, 1:length(' varname ')) = ' varname ';']);
end
end % for


% Resize output data, based on the number of columns (as returned
% from the sscanf of the first line of data) and the total number
% of data elements. Since the data was read in row-wise, and
% MATLAB stores data in columnwise format, we have to reverse the
% size arguments and then transpose the data. If we read in
% irregularly spaced data, then the division we are about to do
% will not work. Therefore, we will trap the error with an EVAL
% call; if the reshape fails, we will just return the data as is.
eval('data = reshape(data, ncols, length(data)/ncols)'';', '');




  簡單的說,這個程式先一行一行判斷是否為string(if ~isstr(line)),然後在以data = [data; fscanf(fid, '%f')];讀入數值資料,並且會以[data, ncols, errmsg, nxtindex] = sscanf(line, '%f');(其中line是先讀入一行)去看ncols。

  最後再把讀入的數值data資料用reshape的方式(data = reshape(data, ncols, length(data)/ncols);)完成。速率的確加快許多。

2 意見:

Ching Ching 提到...

還是有辦法用 textread喔
你這個是有header的 裡面有參數
可以跳過喔
這樣 一行就搞定了

Eric Wu 提到...

感謝您的分享~~