Reputation: 29
I want to store each S I calculate in my for loop to store into a vector, so that I can plot S vs. x. i.e. S(x1),S(x1+0.1)..... will be stored as [S(x1) S(x1+0.1)....] Here's my code:
function[S]=spline(m0,m1,p,q,x1,x2,x)
S=0;
x=x1;
for x=x1:.1:x2
S=(-m0/(6*(x2-x1)))*((x-x2)*(x-x2)*(x-x2))+(m1/(6*(x2-x1)))*((x-x1)*(x-x1)*(x-x1))+p*(x2-x)+q*(x-x1);
end
I can't seem to iteratively store each S in a vector. Thanks for any help.
Upvotes: 0
Views: 305
Reputation: 1012
You need to use an index for S
. In you problem you can't use the one defined in your for loop so you need to use an other one. Also, if you want to plot it correctly you need to define one of your axis according to your 0.1 step.
function[S]=spline(m0,m1,p,q,x1,x2,x)
S=zeros(1,(x2-x1)/0.1 + 1));
x=x1;
i=1;
for x=x1:.1:x2
S(i)=(-m0/(6*(x2-x1)))*((x-x2)*(x-x2)*(x-x2))+(m1/(6*(x2-x1)))*((x-x1)*(x-x1)*(x-x1))+p*(x2-x)+q*(x-x1);
i=i+1;
end
end
You can then plot this vector : plot(linspace(x1,x2,(x2-x1)/0.1 + 1),S)
Upvotes: 1
Reputation: 16193
You are not indexing S
in your loop. A cheap way to achieve what you want would be
idx = 0;
for x=x1:.1:x2
idx=idx+1;
S(idx)=...
Upvotes: 0