Plot a for-loop with if-statements inside

조회 수: 2 (최근 30일)
Viktor Karlsson
Viktor Karlsson 2022년 2월 7일
답변: Rik 2022년 2월 7일
I have written three different functions for three different intervals on the variable r. I wrote the following code:
a = 1;
b = 2;
pv = 5*10^(-3);
Q = pv*((4*pi*b^3)/3) - pv*((4*pi*a^3)/3);
epsilon = 8.8541878176*10^(-12);
r = 0:0.01:10
hold on
for r = 0:0.01:10
if r<a
E = -(Q/(4*pi*epsilon*r^2));
elseif r>b
E = (Q/(4*pi*epsilon*r^2));
else a<r<b
E = (pv*r)/(3*epsilon) - (pv*a^3)/(3*r^2*epsilon);
end
plot(E,r,'r');
end
hold off
Now, this code does not yield a visable plot, it's just empy. I figured maybe I need to store E of every iteration of the loop in a matrix, but have found no way of solving it.

채택된 답변

Dave B
Dave B 2022년 2월 7일
You're not seeing anything because you're plotting 1001 lines, each of which has only one point. You can fix this by plotting them as markers, or by saving all the points to a vector and using one call to plot (vastly preferred approach). Additionally, the condition in your else statement doesn't do anything, and you have an assignment to the variable r which doesn't do anything, I've removed both below:
1001 line objects containing a marker (heavyweight solution):
a = 1;
b = 2;
pv = 5*10^(-3);
Q = pv*((4*pi*b^3)/3) - pv*((4*pi*a^3)/3);
epsilon = 8.8541878176*10^(-12);
hold on
for r = 0:0.01:10
if r<a
E = -(Q/(4*pi*epsilon*r^2));
elseif r>b
E = (Q/(4*pi*epsilon*r^2));
else %a<r<b
E = (pv*r)/(3*epsilon) - (pv*a^3)/(3*r^2*epsilon);
end
plot(E,r,'r.');
end
hold off
1 line object (lightweight solution):
clf
a = 1;
b = 2;
pv = 5*10^(-3);
Q = pv*((4*pi*b^3)/3) - pv*((4*pi*a^3)/3);
epsilon = 8.8541878176*10^(-12);
rr = 0:0.01:10;
E = nan(length(rr),1);
for i = 1:numel(rr)
r=rr(i);
if r<a
E(i) = -(Q/(4*pi*epsilon*r^2));
elseif r>b
E(i) = (Q/(4*pi*epsilon*r^2));
else %a<r<b
E(i) = (pv*r)/(3*epsilon) - (pv*a^3)/(3*r^2*epsilon);
end
end
plot(E,rr,'r');

추가 답변 (1개)

Rik
Rik 2022년 2월 7일
In this case you don't even need a loop:
a = 1;
b = 2;
pv = 5*10^(-3);
Q = pv*((4*pi*b^3)/3) - pv*((4*pi*a^3)/3);
epsilon = 8.8541878176*10^(-12);
r = 0:0.01:10;
E=NaN(size(r));
L1=r<a;
E(L1)=-(Q./(4*pi*epsilon*r(L1).^2));
L2=r>b;
E(L2)= (Q./(4*pi*epsilon*r(L2).^2));
L3=~(L1&L2);
E(L3)=(pv*r(L3))/(3*epsilon) - (pv*a^3)./(3*r(L3).^2*epsilon);
plot(E,r,'r');xlim([-20e11 2e11])

카테고리

Help CenterFile Exchange에서 Mathematics and Optimization에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by