Only storing final for loop values

11 views (last 30 days)
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 Comment
per isakson
per isakson on 3 Apr 2019
Did you try to replace
I1= (abs(psi(1,1))).^2;
by
I1(:,n)= (abs(psi(1,1))).^2;
?

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!