Try this:
opt = {'MultipleDelimsAsOne',true,'CollectOutput',true};
str = 'X';
dtv = [];
dat = {};
fid = fopen('data.txt','rt');
while ischar(str)
while ~strcmp(str(1),'*')
str = fgetl(fid);
end
dtv(end+1,:) = str2double(regexp(str(2:end),'\S+','match'));
pos = ftell(fid);
str = fgetl(fid);
if ischar(str)
N = numel(regexp(str(5:end),'\S+','match'));
fmt = repmat('%f',1,N);
fseek(fid,pos,'bof');
dat{end+1} = textscan(fid,['%4[^*]',fmt],opt{:});
end
end
dat = vertcat(dat{:});
mat = vertcat(dat{:,2});
This reads the entire data matrix (between the date vectors) into a numeric matrix inside the cell array dat, and the date vectors in dtv. It automatically adjusts for the different numbers of columns in your matrices. Some important assumptions:
- the first columns comprise of exactly four characters (which may be spaces).
- the date vectors always start with asterisks, but no other lines do.
- no empty lines between the date vectors and the data matrices.
- the matrices contain numeric data only.
Have a look inside dat, and pick the data that you need:
>> cell2mat(cellfun(@(m)m(1,[1,2,3]),dat(:,2),'UniformOutput',false))
ans =
1.0e+04 *
0.6445 -2.4080 -0.8935
0.6645 -2.2892 -1.1498
I also concatenated the matrices into mat, which lets gives you all of the matrices in one. This might be easier to access:
>> mat([1,10],[1,2,3])
ans =
1.0e+04 *
0.6445 -2.4080 -0.8935
0.6645 -2.2892 -1.1498
I tested this code on both of the files that you have provided (this question, and your last question), which are also available here:
Best Answer