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 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by