Plotting values from a for loop

조회 수: 6 (최근 30일)
Fahad Ahmed
Fahad Ahmed 2016년 12월 1일
댓글: KSSV 2016년 12월 1일
Hi all!
I want to plot the values from the for loop in this code
h = 10^-6;
n2 = 1.5*(10^-18);
p = 1.27;
A = 0.685*(10^-6);
l = 6*(10^-3);
L = 2300 * 10^-9;
E = 8.85 * 10^-12;
n = 3.75;
B = 2*pi/L
c = 3 * 10^8;
w = c * B;
Ex = (2 * 25) * 10^-6;
g = ((n2*w)/(c*A))
Ax = 10^9;
Ay = 10^7;
ii = 0;
for z = 0:h:l;
ii = ii + 1;
Axx = Ax + (h*ii)*((g * abs(Ax^2)) + ((2*p/3) * abs(Ay^2)*Ax) + ((ii*g*p/3)*conj(Ax)*(Ay^2)*exp(1)^(-2*ii*B*z)));
Ayy = Ay + (h*ii)*((g * abs(Ay^2)) + ((2*p/3) * abs(Ax^2)*Ay) + ((ii*g*p/3)*conj(Ay)*(Ax^2)*exp(1)^(-2*ii*B*z)));
LL = ii;
end
figure(1);
plot(LL, Axx);
figure(2);
plot(LL, Ayy);
But when I run the code, the plots are blank. Is this because the variables I'm plotting only have scope inside the loop or is there another reason? How can I plot the values? Thanks!
  댓글 수: 1
Jan
Jan 2016년 12월 1일
Note: While 1.5*(10^-18) is an expensive power operation, 1.5e-18 is a cehap constant. It will not matter the runtime measurably, but it is a good programming practize to prefer cheap code in general.

댓글을 달려면 로그인하십시오.

답변 (1개)

KSSV
KSSV 2016년 12월 1일
clc; clear all ;
h = 10^-6;
n2 = 1.5*(10^-18);
p = 1.27;
A = 0.685*(10^-6);
l = 6*(10^-3);
L = 2300 * 10^-9;
E = 8.85 * 10^-12;
n = 3.75;
B = 2*pi/L
c = 3 * 10^8;
w = c * B;
Ex = (2 * 25) * 10^-6;
g = ((n2*w)/(c*A))
Ax = 10^9;
Ay = 10^7;
ii = 0;
loop = 0:h:l ;
LL = zeros(size(0:h:l)) ;
Axx = LL;
Ayy = LL ;
for i = 1:length(loop)
z = loop(i) ;
ii = ii + 1;
Axx(i) = Ax + (h*ii)*((g * abs(Ax^2)) + ((2*p/3) * abs(Ay^2)*Ax) + ((ii*g*p/3)*conj(Ax)*(Ay^2)*exp(1)^(-2*ii*B*z)));
Ayy(i) = Ay + (h*ii)*((g * abs(Ay^2)) + ((2*p/3) * abs(Ax^2)*Ay) + ((ii*g*p/3)*conj(Ay)*(Ax^2)*exp(1)^(-2*ii*B*z)));
LL(i) = ii;
end
figure(1);
plot(LL, Axx);
figure(2);
plot(LL, Ayy);
It has to be further refined...
  댓글 수: 2
Fahad Ahmed
Fahad Ahmed 2016년 12월 1일
Works like a charm! Thanks, sorry for being newbie :)
KSSV
KSSV 2016년 12월 1일
Consider Jan Simon's comments..

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by