Computation to a matrix iteration not computing the rest of the steps
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Mahmoud Galal
el 21 de Mayo de 2022
Comentada: Mahmoud Galal
el 22 de Mayo de 2022
Hello Everyone, I am fairly new to programming and I am attempting to iterate through a matrix that I succeffully computed (not shown here so it doesnt become too long)
cpot2 = zeros(size(10))
%j = 0
%fcomp = (p*copt3(1,j+1))+(q*copt3(1,j+2))*exp(r*dt)
for j = 0
for s = 1
cpot2 = (p*cpot3(j+1,1))+(q*cpot3(s+1,1))*exp(r*dt)
end
end
Basically it should do 2 more computations, one of which, the last iteration which should be substituted into cpot2, equal to zero. Unfortunately I am only getting the first result of my computation
Any help is appreciated!
4 comentarios
dpb
el 21 de Mayo de 2022
Editada: dpb
el 21 de Mayo de 2022
zeros(size(10))
doesn't do what you think it does/want...try it at command line and see. And 10 isn't the size you need anyways, your loop goes over six values in each dimension, but you reference j+1 and s+1 so the sizes will end up at 6 and 7 .
It's not at all clear what you're trying to do here...where does the idea about "3 iterations" come from? There's no "3" in sight over the loop indices.
As written the above for each iteration over j is the equivlent of
cpot2=(p*cpot3(1)+q*sum(cpot3(2:7)))*exp(r*dt); % j=0
cpot2=(p*cpot3(2)+q*sum(cpot3(2:7)))*exp(r*dt); % j=1
...
cpot2=(p*cpot3(6)+q*sum(cpot3(2:7)))*exp(r*dt); % j=5
I'm guessing this is probably not what you're intending, but we have no way to guess what that might be.
Respuesta aceptada
Mahmoud Galal
el 22 de Mayo de 2022
2 comentarios
John D'Errico
el 22 de Mayo de 2022
Editada: John D'Errico
el 22 de Mayo de 2022
That is AN answer. But not necessarily THE answer, or even the best way to write that code.
You don't need to define cpot0, BEFORE then creating cpot0. So this next line was completely superfluous:
cpot0 = 0
Next, you could have written far simpler code in the first place. That is, as long as cpot3 is a vector of length 4, just write these three lines:
cpot2 = (p*cpot3(1:3) + q*cpot3(2:4)))*disc;
cpot1 = (p*cpot2(1:2) + q*cpot2(2:3))*disc;
cpot0 = (p*cpot1(1) + q*cpot1(2))*disc;
So you could have written it with no loops needed at all. Could you have written it in one line of code, creating a matrix as a result? Probably. And that is better, because then you need not create those numbered variables. Numbered variable names are always a bad idea. But I'll stop before I get to that point, as the code to do it in one line would look a bit confusing, and that would mean it is difficult to debug and follow.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!