Calculation with for loop saving the output in separate variables

Example 1
% Initiate A and x
A=[2 2; 1 3]
x=[0.5; 1]
% Create a for loop
for i = 1:100
x=A*x, x=x/max(x)
end
Example 2
A=[2 2; 1 3]
x=[0.5; 1]
x=x/max(x);
A1=A*x
x=x/max(x);
A2=A*A*x
x=x/max(x);
A3=A*A*A*x
I want to normalize x in each step of a new calculation. As you can see I store the result in a separate variable in the second example. I also want to do that for the for-loop, is that possible?

1 个评论

"is that possible?"
It is certainly possible, if you want to force yourself into writing inefficient, slow, complex, obfuscated, buggy code that is hard to debug. Read this to know more:
The simple and very efficient MATLAB approach is to use indexing.

请先登录,再进行评论。

回答(1 个)

This is how you should do it:
A=[2 2; 1 3];
x=[0.5; 1];
x=x/max(x);
n=5;
B=cell(1, n);
B{1}=A*x;
for i=2:n
B{i}=A*B{i-1};
end

类别

在 帮助中心 和 File 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