0
votes

I am a beginner in Matlab and have not been able to find an answer to my question so far. Your help will definitely be very much appreciated.

I have 70 matrices (100x100), named SUBJ_1, SUBJ_2 etc. I would like to create a loop so that I would calculate some metrics (i.e. max and min values) for each matrix, and save the output in a 70x2 result matrix (where each row would correspond to the consecutively named SUBJ_ matrix).

I am struggling with both stages - how to use the names of individual variables in a 'for' loop and how to properly save individual outputs in a combined array.

Many thanks and all the best!

3
See related answer. The eval(sprintf(...)) is the code/workaround/hack you want, but please note the warning in the beginning (similar to what Daniel and Jonas mentioned). - Dev-iL

3 Answers

4
votes

Don't use such variable names, create a big cell array named SUBJ and put each Matrix in it.

r=zeros(numel(SUBJ),2)
for idx=1:numel(SUBJ)
   r(idx,1)=min(min(SUBJ{idx}))
   r(idx,2)=max(max(SUBJ{idx}))
end

min and max are called twice because first call creates maximum among rows, second call among columns.

3
votes

Even though this is in principle possible in Matlab, I would not recommend it: too slow and cumbersome to implement.

You could instead use a 3-D matrix (100x100x70) SUBJ which would contain all the SUBJ_1 etc. in one matrix. This would allow you to calculate min/max etc. with just one line of code. Matlab will take care of the loops internally:

OUTPUT(:,1) = min(min(SUBJ,[],1)[],2);
OUTPUT(:,2) = max(max(SUBJ,[],1)[],2);

Like this, OUTPUT(1,1) contains min(min(SUBJ(:,:,1))) and so on...

1
votes

As to how to use the names of individual variables in a 'for' loop, here gives an example:

SUBJ = [];
for idx = 1:70
    term = eval(['SUBJ_',num2str(idx)]);
    SUBJ = [SUBJ; max(max(term)),min(min(term))];
end