# How can i plot with if statement ?

4 views (last 30 days)
maryam ahmaf on 16 Jan 2020
Commented: Guillaume on 16 Jan 2020
>> x=[10 20 30 40 50 ] ;
>> if x==10
y=((10*10^6)*.1523)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==40
y=((10*10^6)*2.73)./ x ;
end
if x==50
y=((10*10^6)*5.5547)./ x ;
end

Star Strider on 16 Jan 2020
Try this:
x=[10 20 30 40 50 ] ;
for k = 1:numel(x)
if x(k)==10
y(k)=((10*10^6)*.1523)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==40
y(k)=((10*10^6)*2.73)./ x(k) ;
end
if x(k)==50
y(k)=((10*10^6)*5.5547)./ x(k) ;
end
end
figure
plot(x, y)
grid
It is necessary to index into both ‘x’ and ‘y’ to do what you want.

#### 1 Comment

Guillaume on 16 Jan 2020
Note (to the OP) that 10*10^6 is better written as 10e6.
A much better design of the above would be:
LUT = [10, 0.1523; ...Look Up Table for x and corresponding coefficiet
20, 0.601;
30, 1.914;
40, 2.73;
50, 5.5547];
x = [10 20 30 40 50];
for k = 1:numel(x)
[found, whichrow] = ismember(x(k), LUT(:, 1));
if found
y(k) = 10e6 * LUT(whichrow, 2) / x(k);
else
error('don''t know how to calculate y(k)');
end
end
figure;
plot(x, y);
grid;
So now if you want to add/remove x values and coefficients you only have one line of a matrix to edit instead of having to copy-paste/delete several lines of codes. It's also a lot clearer what the coefficient are and it avoids having twice the same tests (e.,g. the 20 and 30 test that was repeated originally).