Only storing final for loop values
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Allison Cicero
el 2 de Abr. de 2019
Respondida: Adam Danz
el 3 de Abr. de 2019
I am trying to plot t vs I1 and t vs I2, but only the last value of the loop is being stored. I am very new at this so any help would be great
H= [ 0.5*1i -1; -1 -0.5*1i];
psi0= [1; 0];
for n= 1:0.01:10
t=n;
G= expm(-1i*H*t);
psi= G*psi0;
I1= (abs(psi(1,1))).^2;
I2= (abs(psi(2,1))).^2;
end
plot(t,I1)
plot(t,I2)
1 comentario
per isakson
el 3 de Abr. de 2019
Did you try to replace
I1= (abs(psi(1,1))).^2;
by
I1(:,n)= (abs(psi(1,1))).^2;
?
Respuesta aceptada
Adam Danz
el 3 de Abr. de 2019
You're overwriting the t, I1 & I2 variables on each iteration. At the end of the loop, you're left with only the final values.
Here is a modification of your code so you that can store the values from each loop.
H= [ 0.5*1i -1; -1 -0.5*1i];
psi0= [1; 0];
n = 1:0.01:10; % Moved outside of the loop
I1 = nan(1,length(n)); %allocate the loop variable
I2 = I1; %allocate the loop variable
for i = 1:length(n) % loop through each value of 'n'
G= expm(-1i*H*n(i)); % reference the i-th value of 'n'
psi= G*psi0;
I1(i)= (abs(psi(1,1))).^2; %store values from each iteration
I2(i)= (abs(psi(2,1))).^2; %store values from each iteration
end
plot(n,I1) %now you have 2 vectors to plot
hold on %don't repace the line you just plot; add to it instead
plot(n,I2)

0 comentarios
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!