Help with proper indexing for a programming assignment

조회 수: 2 (최근 30일)
Lavorizia Vaughn
Lavorizia Vaughn 2021년 11월 11일
댓글: Lavorizia Vaughn 2021년 11월 13일
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
Lavorizia Vaughn
Lavorizia Vaughn 2021년 11월 13일
I will give this a try.
Lavorizia Vaughn
Lavorizia Vaughn 2021년 11월 13일
that worked ty

댓글을 달려면 로그인하십시오.

추가 답변 (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