IF not working with vector

4 visualizaciones (últimos 30 días)
Alessandro Cabodi
Alessandro Cabodi el 7 de Abr. de 2020
Comentada: Alessandro Cabodi el 8 de Abr. de 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 comentarios
darova
darova el 7 de Abr. de 2020
What is this?
What about for loop?
Alessandro Cabodi
Alessandro Cabodi el 8 de Abr. de 2020
Since it was not working, I actually tried to implement a while loop. I forgot to remove them when i posted the question.

Iniciar sesión para comentar.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 7 de Abr. de 2020
Editada: Ameer Hamza el 8 de Abr. de 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 comentarios
Ameer Hamza
Ameer Hamza el 8 de Abr. de 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 el 8 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by