1
votes

I'm quite new in Matlab and I would be more than grateful if you can help me with the following issue.

I have a .mat file v7.3 which has 26 matrices with increasing number i.e. Mw1, Mw2, Mw3.....Mw26

I want to load only the first column from each matrix separately to do some calculations and then go to the next one using for loop.

I know that there is the option of using matfile and then load the column that I want i.e.:

firstColB = example.B(:,1); (matlab documentation)

but I don't know how to do it in a loop...

For example:

First I have a .mat file with 26 matrices of 5000x4.

Then I want to load only the first column of matrixn (n=26)

Then do the following

ao=0;
a=[2,4,6,8,10,12,14,16,18,20]; %segments of the tube in cm

for j=1:10;

temp11=find(firstColumn>ao & firstColumn<=a(j)); %firstColumn of the *n*matrix

temp1=firstColumn(temp11,:);

eval(sprintf('A%d = temp1', j));

ao=a(j);

end 

My problem:

This loop will generate 10 new matrices of A1, A2, A3......A10 without indicating that correspond to the first matrix (i.e.Mw1). It should be like A11, A12, A13...A110.

...when I finished with this loop I want automatically to go to the next matrix, and repeat the same but then the A matrices should be like A21, A22, A23....A210 since these new matrices correspond to the second matrix etc.

I hope it makes sence of what I'm trying to do!

2

2 Answers

1
votes

First of all, do not use eval. Anoter thing to avoid are variable names like A1 A2 A3, such a mat file should never have been created in the first place, instead it should contain a cell array A holding the data.

I did not get your full question, but I will provide you some code which will hopefully help you. If you don't know cell arrays and dynamic field names please read the corresponding documentation to understand the code.

First of all, I recommend to use load always with an output argument. This results in a struct containing all data from the mat instead of individual variables:

data=load('test.mat')

Now you can iterate it:

fn=fieldnames(data)
B=cell(1,numel(fn))
for ix=1:numel(fn)
     B{1}=data.(fn{ix})(:,1)
end

For each variable from your mat, this code takes the forst column and stores it in a cell array B.

1
votes

The answer by Daniel covers some important information It should be considered before this answer...

This is an alternate way to access the data from disk

Using the matfile function to create a matfile object and then using dynamic field names with this object

myFile = matfile('myFileName.mat')
for jj = 1:26

    B{jj} = myFile.( sprintf('Mw%i',jj) )(:,1)

end

Why do I post this here

  • I believe fieldnames will give the names in the wrong order for your case... (Mw10 will appear before Mw2)
  • Matfile allows you just load in only the required parts of the required variables