1
votes

There is such function as bsxfun: http://www.mathworks.com/help/techdoc/ref/bsxfun.html however it work in element-by-element mode. I want similar function which works in vector-by-vector mode (and with scalar output).

As illustration I would try to use here bsxfun in such way. As inner function I will use (this is just an example) dot product of vectors.

function f = foo(a,b), f=a'*b; printf("called\n");, end

The above dummy function foo expects 2 vector, the result is scalar. Each time it is called we will see a message.

bsxfun(@foo,[2;3],[1 5;4 3])

The result is:

called
called
ans =

   14   19
    0    0

So, two calls (nice), however instead of a vectors (pair of 2 scalars) we got a matrix. One can say, it will suffice to get just first row in such case, because the matrix is the created in advance by bsxfun, and the rest will be always zeros.

But it is not always a case -- sometimes I got some real values, not only zeros -- and I am afraid some side-effects are involved (the above dot product is the simplest example which came to head).

Question

So, is there a function similar to bsxfun, but which gets vectors and expects a scalar, per each operation of those vectors?

1

1 Answers

1
votes

I don't think there is a built in function, but using arrayfun or cellfun you might be able to do something. Generally arrayfun is also element-wise, but if you first split your larger array into a cell then you can do it:

foo = @(a,b) b*a
y = [2;3];
X = [1 5; 4 3];
% split X into cell array of rows
% apply foo to each row
cellfun(@(x) foo(y,x), num2cell(X,2))
ans = 
    17
    17

I am not sure it would give any speed advantage (I would imagine an explicit loop would be quicker) but sometimes it can be easier to read.