Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab equivalent of Numpy broadcasting?

Tags:

I'm trying to find some way to substract a size 3 vector from each column of a 3*(a big number) matrix in Matlab. Of course I could use a loop, but I'm trying to find some more efficient solution, a bit like numpy broadcasting. Oh, and I can't use repmat because I just don't have enough memory to use it (as it creates yet another 3*(a big number) matrix)...

Is this possible?

like image 353
antony Avatar asked Jul 09 '10 13:07

antony


People also ask

Does matlab have broadcasting?

Matrix broadcasting was added to matlab's recent editions. This is an important step for vectorizing codes. Proper usage of broadcasting reduces memory allocation requirements for matrix matrix operations.

What is broadcasting in matlab?

A broadcast variable is any variable, other than the loop variable or a sliced variable, that does not change inside the loop. At the start of a parfor -loop, the values of any broadcast variables are sent to all workers. This type of variable can be useful or even essential for particular tasks.

How do I broadcast a NumPy array?

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.

Does NumPy have broadcasting?

Broadcasting is the name given to the method that NumPy uses to allow array arithmetic between arrays with a different shape or size.


2 Answers

Loops aren't bad in MATLAB anymore thanks to compiler optimizations like just-in-time acceleration (JITA). etc. Most of the time, I've noticed that a solution with loops in current MATLAB versions is much faster than complicated (albeit, cool :D) one-liners.

bsxfun might do the trick but in my experience, it tends to have memory issues as well but less so than repmat.

So the syntax would be:

AA = bsxfun(@minus,A,b) where b is the vector and A is your big matrix

But I urge you to profile the loopy version and then decide! Most probably, due to memory constraints, you might not have a choice :)

like image 167
Jacob Avatar answered Oct 30 '22 11:10

Jacob


The other answers are a bit out of date -- Matlab R2016b appears to have added broadcasting as a standard feature. An example from that blog post that matches the question:

>> A = ones(2) + [1 5]' A =      2     2      6     6 
like image 30
Nathaniel J. Smith Avatar answered Oct 30 '22 11:10

Nathaniel J. Smith