bsxfun when inputs are scalar and vector
이전 댓글 표시
Hello,
I am having trouble using bsxfun when the function inputs are a scalar and a vector. I would like to speed up a function by using bsxfun instead of a for loop. I provide below a very simple function that illustrates the inputs and the operations I want to perform as well as the error i get:
function C = bsxfun_test(a, vec)
el1 = vec(1);
el2 = vec(2);
el3 = vec(3);
C = (exp(el1)*sqrt(el2) + el3)/a;
end
Works well for one:
>> bsxfun_test(2, [1 2 3])
ans =
3.4221
But has some trouble when I want to vectorize:
bsxfun(@bsxfun_test,[2 3 4],[1,2,3; 4,5,6; 7,8,9])
And the error message:
Error using bsxfun Specified function handle produces invalid output dimensions. The function handle must be a binary elementwise function.
The expected output is a vector of size 3x1 (or 1x3) as follows:
>> [bsxfun(@bsxfun_test,2,[1,2,3]);
bsxfun(@bsxfun_test,3,[4,5,6]);
bsxfun(@bsxfun_test,4,[7,8,9])]
ans =
3.4221
42.6951
777.6867
EDIT: 1) I am running version 2018b
댓글 수: 3
Diego Leal
2018년 10월 26일
@Diego Leal: bsxfun is not the correct tool for what you are trying to do. It will expand scalar dimensions, but it will not contract any dimensions: this means that for your example data:
bsxfun(@bsxfun_test,[2 3 4],[1,2,3; 4,5,6; 7,8,9])
it will return an array whose size is where all scalar dimensions are expanded to the size of the other array. In your case it would return a 3x3 matrix, if the function worked without error.
The real solution is to write vectorized code (e.g. see my answer):
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!