Hello, I'm trying to plot one non-piecewise function and two piecewise functions in one graph but I keep getting an error. I don't understand the two error messages below.

2 views (last 30 days)
clear all; close all; clc;
function y = piecewise1(x)
switch x
case x * (x < 0 & x <= 1)
y = 1*x-(1/2)*x^2;
otherwise
y = 1/2;
end
end
function y = piecewise2(x)
switch x
case x * (x < 0 & x <= 2)
y = 2*x-(1/2)*x^2;
otherwise
y = 2;
end
end
x = 0:0.01:6;
y1 = @(x) 0;
y2 = @(x) piecewise1(x);
y3 = @(x) piecewise2(x);
figure; hold on
b1 = plot(x,y1,'yellow'); M1 = "V_G - V_{th} = 0";
b2 = plot(x,y2,'green'); M2 = "V_G - V_{th} = 1";
b3 = plot(x,y3,'blue'); M3 = "V_G - V_{th} = 2";
xlabel('V_D')
ylabel('I_D/K')
legend([b1,b2,b3], [M1,M2,M3], 'Location', 'NorthWest')

Answers (1)

Alan Stevens
Alan Stevens on 17 Nov 2021
You need to put the non-local functions at the end, as in the following.
There were several other errors. I don't know if my corrections reflect what you were trying to achieve, but I'll leave you to modify the following as required.
x = 0:0.01:6;
y1 = @(x) zeros(size(x));
y2 = @(x) piecewise1(x);
y3 = @(x) piecewise2(x);
figure; hold on
b1 = plot(x,y1(x),'y'); M1 = "V_G - V_{th} = 0";
b2 = plot(x,y2(x),'g'); M2 = "V_G - V_{th} = 1";
b3 = plot(x,y3(x),'b'); M3 = "V_G - V_{th} = 2";
xlabel('V_D')
ylabel('I_D/K')
legend([b1,b2,b3], [M1,M2,M3], 'Location', 'NorthWest')
function y = piecewise1(x)
for i = 1:numel(x)
if (x(i) > 0 & x(i) <= 1)
y(i) = 1*x(i)-(1/2)*x(i)^2;
else
y(i) = 1/2;
end
end
end
function y = piecewise2(x)
for i = 1:numel(x)
if (x(i) > 0 & x(i) <= 2)
y(i) = 2*x(i)-(1/2)*x(i)^2;
else
y(i) = 2;
end
end
end

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!