Simple For Loop Question about Creating Variables
2 views (last 30 days)
Show older comments
Hi,
I would like to work with quite a big amount of variables and would like to know if there is a shortcut to reduce the amount of lines in my code.
I tried using a for loop and replaced the 1,2,3,4,5 etc with i and then run it for the corresponding amount of iterations (in this case i= 1:5), but it didn't work out.
Here is some small example of the issue:
A1 = [100;150];
A2 = [200;250];
A3 = [300;350];
A4 = [400;450];
A5 = [500;550];
A1x = mean(A1);
A2x = mean(A2);
A3x = mean(A3);
A4x = mean(A4);
A5x = mean(A5);
Particularly in the second part of the code, I would like to change 1 to 5 to a more simplified way.
Thanks
0 Comments
Accepted Answer
Star Strider
on 17 Mar 2017
Edited: Star Strider
on 17 Mar 2017
Create a matrix from the ‘A’ vectors, then take the mean of the columns:
A1 = [100;150];
A2 = [200;250];
A3 = [300;350];
A4 = [400;450];
A5 = [500;550];
N = 5;
for k1 = 1:N
A(:,k1) = eval(sprintf('A%d',k1));
end
Ax = mean(A)
EDIT — Added loop.
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!