在matlab中绘制一个简单的函数

时间:2015-04-06 19:15:39

标签: matlab

我正在尝试绘制函数

f:[-10,10] -> R
f(x) = 2*x+8, x<=2
f(x) = 3*x*x, x>2

我的代码:

    function [] = func3()
    X = linspace(-10,10,100);
        if (X<=2)
            Y=2.*X+8;
            plot(X,Y);
        else
            Y=3.*X.*X;
            plot(X,Y);
        end
end

它显示了该功能的图表,但它不是正确的。我不明白为什么会这样。谢谢。

1 个答案:

答案 0 :(得分:2)

仅当if分支的矢量参数包含不同于零的所有条目时,才会输入logical indexing分支。因此,在您的情况下,它永远不会输入,只执行else部分。该部分使用向量X所有值,它应用二次函数。

要执行您想要的操作,请将if替换为{{3}}:

X = linspace(-10,10,100);
ind = X<=2;
Y(ind) = 2*X(ind)+8; %// apply affine part of function only to these values of X
Y(~ind) = 3*X(~ind).^2; %// apply quadratic part of function to the remaining values
plot(X,Y);