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