I have a matrix A
of arbitrary dimensions m
x n
and wish to fill it using an equation, for example, for every element a_ij of A<
An alternative using ndgrid
:
[I, J] = ndgrid(1:m, 1:n);
A = I.^2 + J.^2;
bsxfun based solution -
A = bsxfun(@plus,[1:m]'.^2,[1:n].^2)
bsxfun
performs array expansion
on the singleton dimensions
(i.e. dimensions with number of elements equal to 1) and performs an elementwise operation specified by the function handle
which would be the first input argument to a bsxfun
call.
So for our case, if we use a column vector (mx1
) and a row vector (1xn)
, then with the listed bsxfun
code, both of these vectors would expand as 2D matrices
and would perform elementwise summation of elements
(because of the function handle - @plus), giving us the desired 2D output. All of these steps are executed internally by MATLAB.
Note: This has to be pretty efficient with runtime performance, as bsxfun
is well-suited for these expansion
related problems by its very definition as described earlier.