Shury
Shury

Reputation: 578

Plotting a simple function in matlab

I'm trying to plot the function

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

My code:

    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

It show a graph for the function but it's not the correct one. I can't understand why is that. Thank you.

Upvotes: 0

Views: 53

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112749

The if branch is only entered if its vector argument contains all entries different than zero. So in your case it's never entered, and only the else part is executed. That part uses all values of vector X, to which it applies the quadratic function.

To do what you want, replace the if by logical indexing:

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);

Upvotes: 2

Related Questions