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

12 次查看(过去 30 天)
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.

回答(2 个)

Andrei Bobrov
Andrei Bobrov 2016-9-19
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 个评论
sykim14
sykim14 2016-9-19
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

请先登录,再进行评论。


Guillaume
Guillaume 2016-9-19
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))

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by