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
, i = 1,...,m and j=1,...,n, I would like,
a_ij = i^2 + j^2.
In Matlab filled out manually it would appear similar to this,
A = [1^2+1^2, 1^2+2^2, ..., 1^2+j^2, ..., 1^2+n^2;
2^2+1^2, 2^2+2^2, ..., 2^2+j^2, ..., 2^2+n^2;
.
.
.
i^2+1^2, i^2+2^2, ..., i^2+j^2, ..., i^2+n^2;
.
.
.
m^2+1^2, m^2+2^2, ..., m^2+j^2, ..., m^2+n^2]
and so the first few terms would be:
[2, 5, 10,17,...
5, 8, 13,20,...
10,13,18,25,...
17,20,25,32,...
]
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.
An alternative using ndgrid
:
[I, J] = ndgrid(1:m, 1:n);
A = I.^2 + J.^2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With