Borrar filtros
Borrar filtros

loop with two variables

2 visualizaciones (últimos 30 días)
Ilias Minas
Ilias Minas el 9 de Jul. de 2019
Comentada: Walter Roberson el 25 de Jul. de 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

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Jul. de 2019
Editada: Walter Roberson el 9 de Jul. de 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 comentarios
Ilias Minas
Ilias Minas el 24 de Jul. de 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 el 25 de Jul. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by