Calculation with for loop saving the output in separate variables

2 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 4 Dic 2021
Modificato: Stephen23 il 4 Dic 2021
"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.

Accedi per commentare.

Risposte (1)

Matt J
Matt J il 4 Dic 2021
Modificato: Matt J il 4 Dic 2021
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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by