Given \[ \left ( {\begin {array} {cc} 1 & 2 \\ 3 & 4 \end {array}} \right ) \] Find the mean of each row, and add this mean to each element of the corresponding row. The result should be
\[ \left ( {\begin {array} {cc} 2.5 & 3.5 \\ 6.5 & 7.5 \end {array}} \right ) \]
To subtract the mean, just replace Plus with Subtract below for Mathematica and replace
@plus
with @minus
for Matlab. This shows that Matlab bsxfun
is analogue to
Mathematica’s MapThread.
. The main difference is that Matlab is a little bit more
consistent in this example, since in Matlab all operations are done column wise. Hence
mean(A)
takes the mean of each column (same as Matematica in this one case),
but bsxfun
also acts column wise on the matrix A
, while Mathematica Map and
MapThread act row wise (list of lists). One just needs to be careful about this order
difference.
Mathematica mat = {{1, 2}, {3, 4}}; MapThread[Plus,{mat, Mean@Transpose@mat}] // N
|
{{2.5, 3.5}, {6.5, 7.5}} |