Simple For Loop Question about Creating Variables

2 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2017-3-17
编辑:Star Strider 2017-3-17
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by