loop with two variables

1 view (last 30 days)
Ilias Minas
Ilias Minas on 9 Jul 2019
Commented: Walter Roberson on 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

Accepted Answer

Walter Roberson
Walter Roberson on 9 Jul 2019
Edited: Walter Roberson on 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 Comments
Ilias Minas
Ilias Minas on 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 on 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.

Sign in to comment.

More Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!