How to fill a matrix using an equation in MATLAB?

前端 未结 2 1010
孤独总比滥情好
孤独总比滥情好 2021-01-12 18:44

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<

相关标签:
2条回答
  • 2021-01-12 18:49

    An alternative using ndgrid:

    [I, J] = ndgrid(1:m, 1:n);
    A = I.^2 + J.^2;
    
    0 讨论(0)
  • 2021-01-12 18:51

    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.

    0 讨论(0)
提交回复
热议问题