Help with proper indexing for a programming assignment

2 次查看(过去 30 天)
hi i have the code below. for the line that reads "y = y + (k1 + 2*k2 + 2*k3 + k4) / 6;' I would like to make it "y(i+1) = y(i) + (k1 + 2*k2 + 2*k3 + k4) / 6;" but that doesnt work. i should be computing y(i+1). could someone please tell me what to do so that i have the proper indexing, thanks. I would basically like to assign that y to the I+1 row of my matrix ‘computed’.btw i would have p0osted the assignments question but i dont think thats needed for such a small fix.
cases = [1, 1, 0, 0; pi, 0, 0, exp(-10); 2, 2, 0, 0; 2, 2+exp(-3), 0, 0];
%h=b-a/N;
a=0;
b=100;
N=2000; %steps
h=0.05;
t=(0:0.05:100)';
for k = 1:4 th1_2 = cases(k,1); th2_2 = cases(k,2); w1_2 = cases(k,3); w2_2 = cases(k,4);
y = [th1_2,th2_2,w1_2,w2_2];
computed = [y; zeros(N,4)];
for i = 1:N
k1 = h*fpend(y); %function only wants the coordinate in the y position
k2 = h*fpend(y + k1/2);
k3 = h*fpend(y + k2/2);
k4 = h*fpend(y + k3);
y = y + (k1 + 2*k2 + 2*k3 + k4) / 6; %i need help here. i should be computing y(i+1) terms.
????
end

采纳的回答

Walter Roberson
Walter Roberson 2021-11-11
y = [th1_2,th2_2,w1_2,w2_2];
That is a row vector of length 4.
| would like to make it "y(i+1) = y(i) + (k1 + 2*k2 + 2*k3 + k4) / 6;"
y(1) is th1_2, y(2) is th2_2 -- are you sure you want to be looping extending y when you are using all of y in lines such as k1 = h*fpend(y); ?
If the idea is that you want to keep track of all of the different versions of your 1 x 4 y vector, then you would want a 1 x 4 for the first iteration, another 1 x 4 for the second iteration, and so on. You might, for example, want to use a 2D array, in which the row number was the number of iterations -- like assigning to y(i+1, :)
plot(t,approx(:,2));
Your code does not assign to approx and your code does not use y after it is calculated.
  7 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by