Borrar filtros
Borrar filtros

How Can I Vectorize Function With If Statement?

30 visualizaciones (últimos 30 días)
Joseph
Joseph el 7 de Oct. de 2011
Comentada: Scott Simmons el 28 de Mzo. de 2020
I have a function defined like:
function result = myfunc(x)
if x > 3
result = 0;
else
result = 1;
end
end
And I would like to figure out how to vectorize it such that if I pass a vector x = 1:10 then it gives me back a vector with ones and zeros in the right spot. Instead I get this:
>> x = 1:10;
>> result = myfunc(x);
ans = 1
But I don't want a scalar 1 returned I need a vector returned corresponding to each element of x.
I thought I could do:
v_myfunc = vectorize(myfunc)
But that unfortunately just gave an error so that is apparently not the thing to do.
NOTE My actual function is much more complicated but solving this simple example will fix many of my problems I think so please don't say "Just do result = ones(size(x)); result(x > 3) = 0;" since I really need to vectorize functions with if statements inside and so please answer how I can vectorize such a thing. If someone can help me figure out how to vectorize functions with if statements such as these that will be most helpful.
Thank you!

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 7 de Oct. de 2011
>> a=1:10
a =
1 2 3 4 5 6 7 8 9 10
>> b=arrayfun(@myfunc,a)
b =
1 1 1 0 0 0 0 0 0 0
The point is, if you want your function to be able to deal with vector or matrix, the function has to be designed that way. If the function deals with scalar only, then MATLAB function arrayfun(),cellfun() and structfun() can help you go around.
  2 comentarios
Joseph
Joseph el 7 de Oct. de 2011
Thanks, that does it!
Scott Simmons
Scott Simmons el 28 de Mzo. de 2020
is there a way this could work for multiple inputs to myfunc?

Iniciar sesión para comentar.

Más respuestas (2)

TOSA2016
TOSA2016 el 28 de Abr. de 2019
Editada: TOSA2016 el 10 de Jul. de 2019
This might also help
a = 1:10;
b = 0 * (a>3) + 1 * (a<=3)

Walter Roberson
Walter Roberson el 7 de Oct. de 2011
function result = myfunc(x);
result = zeros(size(x));
idx1 = x>3;
idx2 = (x.^2 + x) > 9;
result(idx1) = 1;
result(idx2) = 2;
result(~(idx1|idx2)) = 3;

Categorías

Más información sobre Interactive Control and Callbacks 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