Help with proper indexing for a programming assignment

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 11 Nov. 2021
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 Kommentare
Lavorizia Vaughn
Lavorizia Vaughn am 13 Nov. 2021
I will give this a try.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by