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)
댓글 수: 1
per isakson
2019년 4월 3일
Did you try to replace
I1= (abs(psi(1,1))).^2;
by
I1(:,n)= (abs(psi(1,1))).^2;
?
채택된 답변
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)

댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!