Clear Filters
Clear Filters

Plotting a piecewise function

3 views (last 30 days)
Ali Kiral
Ali Kiral on 25 Jun 2021
Answered: Walter Roberson on 25 Jun 2021
I have a function m-file, goes like this:
function y=periodic(x);
if x<=1
y=0;
end
if x > 1 & x < 2
y=x-1;
end
if x>=2 & x < 3
y=3-x;
end
if x>=3
y=0;
end
At prompt, when I type
x=0:0.1:4;
plot(x,periodic(x))
MATLAB returns 'Output argument "y" (and maybe others) not assigned during call to..' and points out that 'if x<=1' is in error. What is the problem here?

Accepted Answer

Walter Roberson
Walter Roberson on 25 Jun 2021
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:
  1. loop so that you apply periodic to only one element of x at a time, such as arrayfun(@periodic, x); OR
  2. loop inside periodic() over the elements of what was passed in, using appropriate indexing to set appropriate elements of y; OR
  3. learn how to use logical indexing.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!