x=0:0.1:4;
That is a vector.
plot(x,periodic(x))
You are passing the entire vector to the function.
if x<=1
y=0;
end
You are comparing the entire vector to 1, getting a vector of true and false values. You are then using if with that vector. In MATLAB, when you use if or while with a non-scalar object, then the test is considered true only if all of the values being checked are non-zero. So if all of the values in the vector are <= 1 then you would set y to be a scalar 0.
Likewise, your other if test all of the vector, and if all of the elements satisfy the condition, then y is set to a scalar value in the final case (though a vector value in the middle two cases.)
You need to take one of three approaches:
- loop so that you apply periodic to only one element of x at a time, such as arrayfun(@periodic, x); OR
- loop inside periodic() over the elements of what was passed in, using appropriate indexing to set appropriate elements of y; OR
- learn how to use logical indexing.