need help making a 'for' loop to make a new matrix

5 views (last 30 days)
i have 40 matrixes 13x16
i want to make a new matrix 1x40 with max values
im using this:
for iii=1:40
M(1,iii)=max(max(['m-' num2str(iii,'%01d')]));
but M values are all 109 (max value of each matrix are less than 1)
im nwe to matlab and i found it on internet and dont know if its right or not
  1 Comment
Rik on 20 Jul 2021
You may consider doing the Onramp tutorial (which is provided for free by Mathworks) to get familiar with the Matlab basics.

Sign in to comment.

Answers (2)

Jonas on 20 Jul 2021
Edited: Jonas on 20 Jul 2021
your loop calculates the maximum value of a character array. since the character 'm' has value 109 (see double('m')) and your character numbers are 48 (double('0')) and 57 (double('9')) all max values are 109.
what do you want to do actually, are there variables in your workspace called m1 to m40? if you created your variables earlier it would be better to save all of them in the same variable, e.g. in the size of 13x16x40
short example how to get the max of each matrix then
a=rand([3 3 3])
max(a,[],[1 2])
Jonas on 20 Jul 2021
to be honest there is a direct possibility. but it uses a method that should be avoided. you can use the eval function for that:
M(1,iii)=max(eval(['m-' num2str(iii,'%01d')]),[],'all');
using eval is bad style and should be avoided. it makes the code unreadable and is most of the case a result of bad data organisation. if you have data that belong to each other, try to save them together and don't use the same variable name with different numbers at the end.

Sign in to comment.

Rik on 20 Jul 2021
Having numbered variables is a problem that should be solved when you create those variables. If you have 40 variables with the same name, that probably means it is actually an array, instead of independent variables. Why not make it an array then? With an array you can use a simple for loop to process each element.
%Let's fix the mess first. You should fix it when the variables are
for n=1:40
%since they are all the same size, we don't actually need a cell aray
ans = 1×3
13 16 40
%now we use max. since a few releases back we can use this syntax:
max_vals=max(m_array,[],[1 2]);
%this is 1x1x40, so let's reshape
max_vals = 1×40
0.9824 0.9919 0.9995 0.9946 0.9944 0.9945 0.9773 0.9993 0.9915 0.9999 0.9938 0.9988 0.9975 0.9989 0.9990 0.9976 0.9999 0.9975 0.9996 0.9985 0.9912 0.9979 0.9894 0.9973 0.9994 0.9873 0.9984 0.9984 0.9935 0.9994

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by