How to vectorize(?) user defined function with vector inputs.

11 visualizaciones (últimos 30 días)
sykim14
sykim14 el 19 de Sept. de 2016
Respondida: Guillaume el 19 de Sept. de 2016
I'm struggling with this for several days. I googled and did my best to solve this without for-loop but I couldn't.
First, I have a user-defined function. It has 4 inputs but 3rd and 4th inputs are fixed now. This is the function(I intentionally simplified it). But you may just skip this and just read the part below (Core).
if true
function [output_vec] = myfunc(v1, v2, a, b)
output_vec = zeros(2, 1);
elem1 = quantile(v1, a);
elem2 = quantile(v2, b);
output_vec(1) = sum(v2==elem1);
output_vec(2) = sum(v2==elem2);
end
where v1 and v2 are (n*1) vectors, a and b are scalars.
(Core)
There is an (n*p) matrix, M1, defined by
M1 = [v11, v12, v13, ..... , v1p];
I want to apply myfunc to M1, while fixing other inputs. Using for-loops, I may obtain
M2 = zeros(2, p)
for ii = 1:p
M2(:, ii) = myfunc(M1(:, ii), v2, 0.25, 0.75);
end
But I want to avoid for-loop(because p is very large), is there a way to I can get the M2 just like
M2 = myfunc(M1, v2, 0.25, 0.75)
p.s. - As I mentioned, I intentionally simplifed myfunc. So I think vectorizing myfunc by line-by-line is not possible in my case. I just wish to get a solution to vectorze(?) vector-input functions, which can be applied to general situations.
Thanks for reading this long question.

Respuestas (2)

Andrei Bobrov
Andrei Bobrov el 19 de Sept. de 2016
function [output_vec] = myfunc(v1, v2, a, b)
output_vec = zeros(2,size(v1,2));
el2 = quantile(v2, b);
el1 = v1(id,:)+diff(v1([id,id+1],:))./diff(ii([id,id+1])).*(a-ii(i0));
output_vec(1,:) = any(bsxfun(@eq,el1,v2(:)));
output_vec(2,:) = any(el2 == v2 );
end
  1 comentario
sykim14
sykim14 el 19 de Sept. de 2016
Thanks for your effort. However, as I mentioned my actual "myfunc" is much more complicated so I need some kind of general answer. Maybe I should vectorize line by line as you did but...I hope it will not be the case

Iniciar sesión para comentar.


Guillaume
Guillaume el 19 de Sept. de 2016
If you really want to vectorise your code, then it is indeed myfunc that needs to be modified as per Andrei's answer. Without the actual code of myfunc, we can't really help you.
The following would be some sort of vectorising of the loop but may actually be slower than an explicit loop due to the anonymous function call and cell array conversions:
cell2mat(cellfun(@(row) myfunc(row, v2, 0.25, 0.75), num2cell(M1, 2), 'UniformOutput', false))
or using arrayfun (which avoids one cell array conversion):
cell2mat(arrayfun(@(rowidx) myfunc(M1(rowidx, :), v2, 0.25, 0.75), (1:size(M1, 1)', 'UniformOutput', false))

Categorías

Más información sobre MATLAB Coder en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by