Help with proper indexing for a programming assignment

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 日

0 投票

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 件のコメント

Lavorizia Vaughn
Lavorizia Vaughn 2021 年 11 月 11 日
編集済み: Lavorizia Vaughn 2021 年 11 月 11 日
i have fixed my code. i have deleted the plot and made some necessary corrections. I have put question marks where i have left space for the code of assigning the y variables properly.
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 11 月 11 日
I would like to basically assign the y-variable on the legs to the i+1 row of matrix ‘computed’.
Walter Roberson
Walter Roberson 2021 年 11 月 11 日
computed(i+1,:) = y;
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 11 月 11 日
is there any other way of writing this?
Walter Roberson
Walter Roberson 2021 年 11 月 13 日
for C = 1 : size(computed,2)
computed(i+1,C) = y(C);
end
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 11 月 13 日
I will give this a try.
Lavorizia Vaughn
Lavorizia Vaughn 2021 年 11 月 13 日
that worked ty

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by