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 Comment

"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.

Sign in to comment.

Answers (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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 4 Dec 2021

Edited:

on 4 Dec 2021

Community Treasure Hunt

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

Start Hunting!