IF not working with vector
4 views (last 30 days)
Show older comments
Alessandro Cabodi
on 7 Apr 2020
Commented: Alessandro Cabodi
on 8 Apr 2020
Hello, sorry for the trivial question.
I wrote this function:
function f = g(m)
%piecewise function evaluation
if m <= 0
f(n) = -2*m;
else
f(n) = 2*m;
end
end
Which actually works when g is given numbers individually
g(2) = 2, g(-2) = 2
However when I try to plot it by evaluting the function g in an array of value in x created with linspace it seems to "forget" about if condition in the function statement.
x = linspace(-1,1);
g(x) = "gives a straight line 2x, instead of behaving like abs(2x)"
2 Comments
Accepted Answer
Ameer Hamza
on 7 Apr 2020
Edited: Ameer Hamza
on 8 Apr 2020
IIf you want to write your own function with if-else block look to implement abs function, then you will need to write a loop
function f = g(m)
%piecewise function evaluation
for i=1:numel(m)
if m(i) <= 0
f(i) = -2*m(i);
else
f(i) = 2*m(i);
end
end
end
Or a one-liner if your question is specifically related to abs(2*m);
function f = g(m)
f = 2*m.*(m>0) - 2*m.*(m<0);
end
6 Comments
Ameer Hamza
on 8 Apr 2020
"are your suggestions sort of the only easy ways to do it"
easy is a subjective term. You can say that it requires the least number of statements. Someone might say that following is the "easiest"
function f = g(m)
f = 2*m;
f(f<0) = -f(f<0);
end
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!