plot variable values of loop

Hello
I have a code like this
for k=1:3
%something
if %one condition
d=d-2
if %the other condition
d=d+3
end
end
end
Basically I've written a loop in which I change the value of d
I have 3 iterations and 3 values of d.
I want to plot the values of d against the iteration's number, so that the x axis will be the iteration numbers and the y axis will be the values of d. How can I do this?
I've searched similar questions but haven't found like this one.
Thank you

6 Commenti

Possibly it will work to save the values of d?
d = zeros(4,1);
d(1) = 0; % put initial value for d here
for k=1:3
%something
if %one condition
d(k+1)=d(k)-2
elseif %the other condition
d(k+1)=d(k)+3
end
end
plot(1:3,d(2:end))
That is great, but it gives me errors. I have an .m file like this
%something......
d=zeros(p+1,1)
d(1)=0.2
p=3
for k=1:p
%parameterized function
a=2; b=2; c=0.5; e=0.5;
u_g = @(x, x_e, N)(-0.5*a*x.^2+b*(x-x_e)-c*N+e*u_p(x,x_e,N, d(k)));
%something......
p=(u_p(Z(:,1), Z(:,3), Z(:,2),d(k)).');
if %one condition
d(k+1)=d(k)-2
elseif %the other condition
d(k+1)=d(k)+3
end
end
plot(1:p,d(2:end))
and I have one function file
function u=u_p(x,x_e,N,d)
u = -(x-x_e).^2+N.*d(k);
end
can I change the value of d in function file or in the loop? I want to change it in every iteration and then make my calculations based on d's new value. but there are some errors like this
Undefined function or variable 'k'.
Error in u_p (line 3)
u = -(x-x_e).^2+N.*d(k);
Error in game>@(x,x_e,N)(-0.5*a*x.^2+b*(x-x_e)-c*N+e*u_p(x,x_e,N,d(k)))
Error in game (line 36)
g=(u_g(Z(:,1),Z(:,3), Z(:,2) ).');
>>
Rik
Rik il 3 Apr 2020
Since you are providing only one value of d to your subfunction you don't need to index it again.
Ani Asoyan
Ani Asoyan il 3 Apr 2020
so should I delete all the indexes or only the index in the function? that doesn't work either way
If you indeed call your function with this
p=u_p(Z(:,1), Z(:,3), Z(:,2),d(k)).';
then your function should look like this
function u=u_p(x,x_e,N,d)
u = -(x-x_e).^2+N.*d;
end
Ani Asoyan
Ani Asoyan il 3 Apr 2020
Modificato: Ani Asoyan il 3 Apr 2020
I got it ! Thank you sooo much!!

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 2 Apr 2020

Modificato:

il 3 Apr 2020

Community Treasure Hunt

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

Start Hunting!

Translated by