Calling in a function inside a for loop and storing each answer separetly

Hello, this is my code so far. My function outputs the number of iterations needed to solve a system, and I want to use this script to output the number of iterations but with varying a parameter as shown:
A = [-10 4 1 0; 4 -10 0 1; 1 0 -10 4; 0 1 4 -10];
B = [-200;-80;-300;-180];
n = 4;
x = [0;0;0;0];
imax = 1000;
es = 1e-6;
w= 1.2;
for w=0.1: 0.1: 1.9
engr3202_gsrelax(A,B,n,x,imax,es, w);
end
I keep getting large numbers of iterations so i'm not sure if the code is just adding them all together, but i basically want 19 outputs separately so i can plot a graph with it.
Thanks a lot!

 Respuesta aceptada

Walter Roberson
Walter Roberson el 2 de Nov. de 2019
Editada: Walter Roberson el 2 de Nov. de 2019
A = [-10 4 1 0; 4 -10 0 1; 1 0 -10 4; 0 1 4 -10];
B = [-200;-80;-300;-180];
n = 4;
x = [0;0;0;0];
imax = 1000;
es = 1e-6;
wvals = 0.1: 0.1: 1.9;
for widx = 1 : length(wvals)
w = wvals(widx);
gs(widx,:) = engr3202_gsrelax(A,B,n,x,imax,es, w);
end
plot(wvals, gs)

3 comentarios

gs(widx,:) = engr3202_gsrelax(A,B,n,x,imax,es, w);
Could you explain why you put a colon here?
Thank you
We do not know the size of your output for each call. Using the colon allows for the possibility that you return a vector for each call.
Okay, this really helped. Thanks a lot!

Iniciar sesión para comentar.

Más respuestas (1)

Bhaskar R
Bhaskar R el 2 de Nov. de 2019
Editada: Bhaskar R el 2 de Nov. de 2019
You have not provided the output varibles of the function engr3202_gsrelax(A,B,n,x,imax,es, w);
Make output variables in the calling, I assume only one variable here, say output and intialize with length of w
A = [-10 4 1 0; 4 -10 0 1; 1 0 -10 4; 0 1 4 -10];
B = [-200;-80;-300;-180];
n = 4;
x = [0;0;0;0];
imax = 1000;
es = 1e-6;
w= 1.2;
w=0.1: 0.1: 1.9;
output = zeros(1, length(w));
for iw=0.1: 0.1: 1.9
output(:, iw) = engr3202_gsrelax(A,B,n,x,imax,es, iw);
end
You can get the data in the variable output for all your loop iterations(19 in our case)

4 comentarios

Now, this will not work. You are trying to use the non-integer iw as an index into output(). And
length(w=0.1: 0.1: 1.9)
is not valid syntax.
Yes, I corrected now. Thanks
output(:, iw) = engr3202_gsrelax(A,B,n,x,imax,es, iw);
Could you explain the colon here?
Thank you
Never mind, I understand now.
Thanks a lot for your help!

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 2 de Nov. de 2019

Comentada:

el 2 de Nov. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by