Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a matrix using an equation in MATLAB?

Tags:

matrix

matlab

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,...
]
like image 637
Little Bobby Tables Avatar asked Sep 17 '14 08:09

Little Bobby Tables


2 Answers

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.

like image 169
Divakar Avatar answered Sep 19 '22 08:09

Divakar


An alternative using ndgrid:

[I, J] = ndgrid(1:m, 1:n);
A = I.^2 + J.^2;
like image 33
Dan Avatar answered Sep 20 '22 08:09

Dan