# Plot a for-loop with if-statements inside

1 view (last 30 days)
Viktor Karlsson on 7 Feb 2022
Answered: Rik on 7 Feb 2022
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 on 7 Feb 2022
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'); Rik on 7 Feb 2022
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]) ### Categories

Find more on Elementary Math in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!