Hassan Saif
Hassan Saif

Reputation: 1062

Load multiple-martrix file into Matlab

I have a file that contains multiple numerical matrices. All matrices are separated by newline as shown in the example below:

0,-1,18
1,2,1
2,-1,7
3,-1,12
4,-1,7

5,-1,23
6,-1,18
7,-1,10
5,-1,23
8,2,9
9,2,8

15,-1,1
128,-1,7
174,-1,8
175,-1,0
176,-1,7

I wanna load this file into Matlab workspace so that each matrix will be assigned to a different variable.

Matlab provides a simple load function that apparently doesn't work for such kind of format.

It would be very useful if you have any clue of how load such file.

Many thanks

Upvotes: 1

Views: 1066

Answers (3)

yuk
yuk

Reputation: 19870

The code below reads all the lines with TEXTSCAN, splits them to separate matrices by empty lines, then converts to double.

As a result you get cell array out with double matrices as individual cells. For example to access the 1st matrix use out{1}, etc. It's better than individual variables.

%# open file and read all lines
fid = fopen('test6.txt','rt');
temp = textscan(fid, '%s', 'delimiter', '\n');
temp = [temp{:}];
fclose(fid);

%# find empty lines
idxSep = find(cellfun(@isempty, temp));
%# separate matrices to different cells
temp2 = mat2cell(temp, diff([0; idxSep; numel(temp)]), 1);
%# remove empty lines
temp2(1:end-1) = cellfun(@(x) x(1:end-1), temp2(1:end-1), 'UniformOutput',0);

%# convert cell arrays to double
out = cell(size(temp2));
for k = 1:numel(temp2)
    out{k} = cellfun(@str2num, temp2{k}, 'UniformOutput',0);
end
out = cellfun(@cell2mat, out, 'UniformOutput', 0);

I probably missed something to make the code simpler. Any suggestions are welcome.

Upvotes: 1

Hassan Saif
Hassan Saif

Reputation: 1062

Here is my solution

I changed the file to the following format:

n=3 %number of matrices

r=3 %number of raws in the current matrix
0 -1 18
1 2 1
2 -1 7


r=3
3 -1 12
4 -1 7
5 -1 23


r=5
6 -1 18
7 -1 10
5 -1 23
8 2 9
9 2 8


And I implemented the following simple function

function data = load_sparse_data(filename)

% open the file
fid = fopen(filename);
% find N (The total number of matrices)
N = fscanf(fid, 'n=%d\n', 1);

% read each matrix
for n = 1:N
    % skip line
    fscanf(fid, '\n', 1);

    % find R, the number of raws
    R = fscanf(fid, 'r=%d\n', 1);

    % fscanf fills the array in column order,
    % so transpose the results
    data(n).mat  = ...
    fscanf(fid, '%f', [3, R])';

    % skip line
    fscanf(fid, '\n', 1);
end 

%cloes the file
fclose(fid);                

Upvotes: 0

High Performance Mark
High Performance Mark

Reputation: 78306

So import the file into one matrix and split it into the sub-matrices you want. uiimport or dlmread will do the first part of this, you'll have to do the second part.

If your dataset is so large that you can't load it all at once and copy it into other variables, then you'll have to experiment with textscan or similar functions to read the file in chunks.

Upvotes: 0

Related Questions