필터 지우기
필터 지우기

unsure on index notation

조회 수: 2 (최근 30일)
charlie
charlie 2023년 11월 20일
답변: Ravi 2023년 12월 6일
hiya! im currently working on some tutorial stuff for my degree and am tasked with creating some code to run a forward euler method. A lecturer last year used this
for j = 0:2
i = i + 1
blah
end
and it works but i dont really understand why. can someone explain? heres the code im using in full. Im still new to code so be gentle T_T
hold on
h = 0.1;
t = 0: h: 1;
i = 0;
f=@(x)((t.^2)./cos(x));
a=1; b=-2;
tol=1e-4;
c=(a+b)/2;
brack(f,a,b,tol); %using bracketing method to find step 1
x(1) = c;
for j = 0 : h : 1
i = i + 1;
t(i+1) = t(i) + h;
%forward euler for (i+1)
xfe = x(i) + h.*((t(i).^2)./cos(x(i)));
%then backwards
x(i+1) = x(i) + h.*((t(i+1).^2)./cos(xfe));
end
plot(t,x)
  댓글 수: 1
Image Analyst
Image Analyst 2023년 11월 20일
Try adding a comment before every single line and be as descriptive as you can. Often when you explain it to somebody, you understand it better yourself.

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

답변 (1개)

Ravi
Ravi 2023년 12월 6일
Hi Charlie,
I assume you are facing trouble understanding the different uses of the for-loop indexing. The first one uses a: b notation, and the second one uses a: step: b notation.
for j = 0:2
i = i + 1
blah
end
In this case “j” takes only integers starting from 0 and ending at 2. That is, the code section in the loop executes for “j” values 0, 1, and 2.
for j = 0:h:1
i = i + 1;
end
In this case, “j” is not restricted to take only integer values. Instead, “j” starts at “a” and is incremented by “step” every time until the value of j does not exceed “b”.
Hope this helps you understand the indexing better.
Thanks,
Ravi Chandra

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by