Only storing final for loop values

11 次查看(过去 30 天)
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)

采纳的回答

Adam Danz
Adam Danz 2019-4-3
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by