编写一个自定义的一元函数分段函数的 Matlab 程序(尽量多种方法),并画出相应图形
时间: 2024-05-19 13:13:50 浏览: 130
方法一:
function y = myfun(x)
if x < -1
y = 0;
elseif x >= -1 && x < 0
y = x + 1;
elseif x >= 0 && x < 1
y = x^2;
else
y = 1;
end
x = -2:0.01:2;
y = arrayfun(@myfun, x);
plot(x, y)
方法二:
x = -2:0.01:2;
y = zeros(size(x));
idx1 = x < -1;
idx2 = x >= -1 & x < 0;
idx3 = x >= 0 & x < 1;
idx4 = x >= 1;
y(idx1) = 0;
y(idx2) = x(idx2) + 1;
y(idx3) = x(idx3).^2;
y(idx4) = 1;
plot(x, y)
方法三:
x = -2:0.01:2;
y = zeros(size(x));
y(x < -1) = 0;
y(x >= -1 & x < 0) = x(x >= -1 & x < 0) + 1;
y(x >= 0 & x < 1) = x(x >= 0 & x < 1).^2;
y(x >= 1) = 1;
plot(x, y)
图形:见下图
![分段函数图像](https://img-blog.csdnimg.cn/20210726111407278.png)
阅读全文