Only storing final for loop values

11 Ansichten (letzte 30 Tage)
Allison Cicero
Allison Cicero am 2 Apr. 2019
Beantwortet: Adam Danz am 3 Apr. 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 Kommentar
per isakson
per isakson am 3 Apr. 2019
Did you try to replace
I1= (abs(psi(1,1))).^2;
by
I1(:,n)= (abs(psi(1,1))).^2;
?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
Adam Danz am 3 Apr. 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)
190403 083838-Figure 1.jpg

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by