How to fill a matrix using an equation in MATLAB?

I have a matrix A arbitrary sizes m x n and I want to fill it using the equation, for example, for each element a_ij A , i = 1, ..., m and j = 1, ..., n, I would like

a_ij = i ^ 2 + j ^ 2.

In manually filled matlab, it will look like this one,

 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 therefore the first few terms will be:

 [2, 5, 10,17,... 5, 8, 13,20,... 10,13,18,25,... 17,20,25,32,... ] 
+6
source share
2 answers

Alternative using ndgrid :

 [I, J] = ndgrid(1:m, 1:n); A = I.^2 + J.^2; 
+4
source

bsxfun solution -

 A = bsxfun(@plus,[1:m]'.^2,[1:n].^2) 

bsxfun performs array expansion on singleton dimensions (i.e., sizes with the number of elements equal to 1), and performs elementwise operation specified by the function handle which will be the first input argument to the bsxfun call.

So, for our case, if we use column vector (mx1 ) and row vector (1xn) , then with the specified bsxfun code bsxfun both of these vectors will expand as 2D matrices and will perform elementwise summation of elements (due to the function descriptor @plus ), giving us the desired 2D output. All these steps are performed inside MATLAB.

Note. This should be quite effective at runtime performance, since bsxfun well suited for these related expansion problems by the very definition described earlier.

+8
source

Source: https://habr.com/ru/post/975406/


All Articles