- 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.
Plotting a piecewise function
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Ali Kiral
il 25 Giu 2021
Risposto: Walter Roberson
il 25 Giu 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?
0 Commenti
Risposta accettata
Walter Roberson
il 25 Giu 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:
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!