Is it possible to vectorize for only one input?

Suppose there are two variables.
v1 = [1 2 3];
m1 = [1 2 3; 4 5 6];
I hope to create another matrix m2, having the same size with m1, and its (i, j) component is defined by
m2(i, j) = sum(v1 > m1(i, j))
In this case, clearly one solution is use "for" loop twice.
m2 = zeros(2, 3);
for i = 1:2
for j = 1:3
m2(i, j) = sum(v1 > m1(i, j));
end
end
However I want to know whether we can apply vectorization for the above procedure. To do this, I first thought that I may create an anonymous function
test_opr = @(v, x) sum(v > x);
and vectorize for the only latter input(while fixing v). But I couldn't find a proper way to do this. Is there any useful trick or alternative?
Thanks in advance.

 채택된 답변

José-Luis
José-Luis 2016년 6월 29일
편집: José-Luis 2016년 6월 29일

1 개 추천

v1 = [1, 2, 3]; m1 = [1, 2, 3; 4, 5, 6];
your_result = arrayfun(@(x) sum(v1 > x), m1)
Though this is just syntactic sugar around looping. Maybe faster, would need to test:
v1 = reshape(v1,1,1,[]);
alt_result = sum(bsxfun(@lt,m1,v1),3)

댓글 수: 2

sykim14
sykim14 2016년 6월 29일
편집: sykim14 2016년 6월 29일
Thanks! Your answer helped me a lot. Not just for this specific case, your answer helped me understand arrayfun and bsxfun more deeply.
My pleasure.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 6월 29일

댓글:

2016년 6월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by