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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by