IF not working with vector

4 Ansichten (letzte 30 Tage)
Alessandro Cabodi
Alessandro Cabodi am 7 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 Kommentare
darova
darova am 7 Apr. 2020
What is this?
What about for loop?
Alessandro Cabodi
Alessandro Cabodi am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 7 Apr. 2020
Bearbeitet: Ameer Hamza am 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 Kommentare
Ameer Hamza
Ameer Hamza am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by