Question

I have a function f which should give me a matrix where x is subtracted element wise from m

m = ones(4);
f = @(x) m-x;

when I call this function with

f(5)

everything works fine.

But how can I call this function with a vector

f([5,7])

so I get

-4    -4    -4    -4
-4    -4    -4    -4
-4    -4    -4    -4
-4    -4    -4    -4

and

-6    -6    -6    -6
-6    -6    -6    -6
-6    -6    -6    -6
-6    -6    -6    -6

in something like a 3-dimensional matrix.

If possible I'm searching for the most efficient way to do this, so I do not want to use loops.

Thank you for your help!

Was it helpful?

Solution

You don't need to define a function for that. Just shift the vector to the third dimension and use bsxfun:

m = ones(4);
v = [5 7];
bsxfun(@minus, m, shiftdim(v(:),-2))

OTHER TIPS

To add to Luis Mendo's accepted answer, you can use permute to rearrange the dimensions of the vector if that is more intuitive to you than shiftdim:

v = [5 7];
bsxfun(@minus, m, permute(v,[3 1 2])) % 4x4x1 @minus 1x1x2 => 4x4x2

With bsxfun, it is all about aligning the non-singleton dimensions. Note that when doing a negative (right) effective shift, you can also use reshape like reshape(v,[1,1,size(v)]) to shift from 1x2 to 1x1x1x2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top