Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Loading a matrix into matlab

Subject: Loading a matrix into matlab

From: Niclas Celvin

Date: 29 Dec, 2009 02:55:07

Message: 1 of 2

Hello

I have a .txt file that looks like this

part:1
1 2 3 4 1
2 3 4 5 2
3 4 5 6 3
part:2
3 4 5 6 1
6 7 8 9 2
1 2 3 4 3
2 3 4 5 4
3 4 5 6 5
part:3
6 7 8 9 1
1 2 3 4 2
2 3 4 5 3

and so on.

I would like to load these matrixes seperatly into matlab so I get one matrix for every part without the heading.

I copy my file into excel, remove the headings and add the matrixes based on the last column that is an index. However, this is not so nice so if anyone knows a nice way I would be very greatful.

Have a nice day

// Niclas

Subject: Loading a matrix into matlab

From: Miroslav Balda

Date: 29 Dec, 2009 23:04:04

Message: 2 of 2

"Niclas Celvin" <ncelvin@abo.fi> wrote in message <hhbr2b$557$1@fred.mathworks.com>...
SNIP
Hi Niclas,
The following code executes your task, provided your data are in the file "Niclas.txt'
% Niclas.txt
part:1
1 2 3 4 1
2 3 4 5 2
3 4 5 6 3
part:2
3 4 5 6 1
6 7 8 9 2
1 2 3 4 3
2 3 4 5 4
3 4 5 6 5
part:3
6 7 8 9 1
1 2 3 4 2
2 3 4 5 3

%--------Niclas.m---------
mtx = {};
mxk = [];

fid = fopen('Niclas.txt');
while 1
    tline = fgets(fid);
    if ~ischar(tline) || tline(1)>'9' % first char is text
        mtx = [mtx, {mxk}];
        mxk = [];
    else
        mxk = [mxk; sscanf(tline,'%f')'];
    end
    if ~ischar(tline), break, end % if EOF
end
fclose(fid);
mtx{2:end} % Matrices in cell array

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us