IF not working with vector

6 views (last 30 days)
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
darova
darova on 7 Apr 2020
What is this?
What about for loop?
Alessandro Cabodi
Alessandro Cabodi on 8 Apr 2020
Since it was not working, I actually tried to implement a while loop. I forgot to remove them when i posted the question.

Sign in to comment.

Accepted Answer

Ameer Hamza
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
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
Alessandro Cabodi
Alessandro Cabodi on 8 Apr 2020
Ok thank you, it's a bit more clear now. I think i'm gonna use the for loop, at my level it is more immediate, thank you however for having clarified the second code.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!