loop with two variables

1 visualizzazione (ultimi 30 giorni)
Ilias Minas
Ilias Minas il 9 Lug 2019
Commentato: Walter Roberson il 25 Lug 2019
Hello,
I am trying to write a code to do a loop with two variables.
I am solving the characteristic equation of a polynomial using the command root and i am taking the eigenvalues.
I want to change two variables (a and b) and do a loop. For every value of b calculate the eigenvalues at the range of a.
For example for a=0:1:3
b=0:1:3
And finally give me the results in a seperate matrix or vector.
Currently i am using arrayfun but only for one variable(a)
How can i do it?
Thank you

Risposta accettata

Walter Roberson
Walter Roberson il 9 Lug 2019
Modificato: Walter Roberson il 9 Lug 2019
avals=0:3;
bvals=0:3;
Numa=length(avals) ;
Numb=length(bvals) ;
Result=cell(Numa, Numb) ;
for aidx = 1:Numa
a = avals(aidx) ;
for bidx = 1:Numb
b = bvals(bidx) ;
Array=something involving a and b
Result{aidx, bidx} = eig(Array) ;
end
end
  3 Commenti
Ilias Minas
Ilias Minas il 24 Lug 2019
Hi Walter,
I want to thank you first of all for your help.
I am using your answer and solved my hands.
However i want to ask you if its possible to do it with three variables. I tried to use the same code that you mentioned but its not working.
let my give you an example
For example for a=0:1:3
b=0:1:3
c=0:1:3
for a=0 and b=0 c=0:1:3
for a=1 and b=0 c=0:1:3 etc
I want all the possible compinations of a and b which are 4 in this case, to run in the whole range of c and have the result in a matrix or vector or cell array.
I would appreciate your help
Thank you again
Walter Roberson
Walter Roberson il 25 Lug 2019
av=0:1:3;
bv=0:1:3;
cv=0:1:3;
[A, B, C] = ndgrid(av, bv, cv);
result = arrayfun(@(a,b,c) FunctionOfThreeVariables(a,b,c), A, B, C)
If the function returns a non-scalar, then add 'uniform', 0 as an option to get a cell array of results.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements 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