Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional element replacement using cellfun

vec = randi(10,10,1)
vec(vec < 5) = 0

func = @(x) x(x < 5) = 0    % This isn't valid

How am I supposed to translate the second line of code into a function handle that I can use in conjunction with cellfun?

like image 779
Andi Avatar asked May 17 '18 14:05

Andi


2 Answers

You can use multiplication, since if your condition is satisfied you have 1 and 0 otherwise.

Multiplying by the inverse of the condition therefore gives you either an unchanged value (if condition is not satisfied) or your desired substitution of 0!

func = @(x) x .* (~(x < 5)) % Replace values less than 5 with 0

If you had a different substitution, you could expand the same logic

func = @(x) x .* (~(x < 5)) + 10 * (x < 5) % replace values less than 5 with 10
like image 71
Wolfie Avatar answered Oct 11 '22 11:10

Wolfie


How about not using an anonymous function, but a function handle instead?

vec = randi(10,10,1);
vec_cell = num2cell(vec);
vec_cell_out = cellfun(@func, vec_cell);

function x = func(x)
    x(x<5) = 0;
end
like image 2
JHBonarius Avatar answered Oct 11 '22 13:10

JHBonarius