I'm interested in plotting the following function in Matlab, but without succes.
I can't manage to plot the points.
x = -1:0.1:3;
if (x<=1)
y = x*x-x+1
plot(x,y)
else
y = 2*x+3
plot(x,y)
end
I'm interested in plotting the following function in Matlab, but without succes.
I can't manage to plot the points.
x = -1:0.1:3;
if (x<=1)
y = x*x-x+1
plot(x,y)
else
y = 2*x+3
plot(x,y)
end
The if
statement you defines takes the condition for the entire array, which means all entries should adhere to the statement. Since only the first 21 adhere to the condition posed, the if
statement goes to the else
and plots a straight line.
Your equation for the first line is incorrect, since x*x
results in an error since MATLAB assumes this to be a matrix multiplication and the sizes are not correct for that. The reason you are not seeing this error is due to the if
statement, since, as explained above, that never reaches this line. You should change that equation using the dot-multiplication, which does things element-wise as opposed to array/matrix-wise.
The equation for the second line is correct.
If your if/else
statement would be correct your first plot would be overwritten by the second, since you did not specify the hold on
switch to figures.
As a note I also used the semicolon ;
after each statement, which prevents it from printing the output of a line to the console.
x1 = [-1:0.01:1].';
x2 = [1:0.01:3].';
y1 = x1.^2-x1+1;
y2 = 2*x2+3;
figure;
hold on
plot(x1,y1)
plot(x2,y2)