unsure on index notation

2 visualizaciones (últimos 30 días)
charlie
charlie el 20 de Nov. de 2023
Respondida: Ravi el 6 de Dic. de 2023
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 comentario
Image Analyst
Image Analyst el 20 de Nov. de 2023
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.

Iniciar sesión para comentar.

Respuestas (1)

Ravi
Ravi el 6 de Dic. de 2023
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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by