Filter löschen
Filter löschen

loop with two variables

2 Ansichten (letzte 30 Tage)
Ilias Minas
Ilias Minas am 9 Jul. 2019
Kommentiert: Walter Roberson am 25 Jul. 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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Jul. 2019
Bearbeitet: Walter Roberson am 9 Jul. 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 Kommentare
Ilias Minas
Ilias Minas am 24 Jul. 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 am 25 Jul. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by