zero padding a matrix

后端 未结 5 675
深忆病人
深忆病人 2021-01-13 19:18

I have a 16X16 matrix. I have to add it to a 256X256 matrix. Can anyone help me how to make this 16X16 matrix into 256X256 filling the remaining with zeros?

相关标签:
5条回答
  • 2021-01-13 19:36

    First thing to do is create an output matrix that is 256x256, assuming you want to keep the original 256x256 matrix pristine. Next, move the values of the input 256x256 matrix into the output matrix. The next step is to add in the 16x16 elements to the output matrix.

    But, before anyone can really answer this, you need to explain how the 16x16 matrix relates to the 256x256 matrix. In other words, is the first element (0,0) of the 16x16 matrix going to be added to the first element (0,0) of the 256x256 matrix? How about the secound element of (0, 1) - do you know where that is going to be added in? What about element (1, 0) of the 16x16 matrix - what element of the 256x256 matrix does that get added into? Once you figure this out, you should be able to simply code some loops to add in each element of the 16x16 matrix to the appropriate 256x256 output matrix element.

    0 讨论(0)
  • 2021-01-13 19:38
    padded = zeros(256,256);
    data = rand(16,16);
    padded(1:16,1:16) = data;
    
    0 讨论(0)
  • 2021-01-13 19:44

    So, this doesn't actually answer your question, but I think it answers the use case you gave. Assuming you want to add the smaller matrix to the upper-left corner of the big matrix:

    big = ones(256, 256);
    small = ones(16, 16);
    big(1:16, 1:16) = big(1:16, 1:16) + small;
    

    This avoids allocating an extra 65000 or so doubles which you would have to do if you re-sized small from 16x16 to 256x256.

    0 讨论(0)
  • 2021-01-13 19:47

    Matlab automatically pads with zeros if you assign something to an element outside of the original size.

    >> A = rand(16, 16);
    >> A(256, 256) = 0;
    >> size(A)
    ans =
       256   256
    
    0 讨论(0)
  • 2021-01-13 19:47

    Use padarray function in Matlab. Use Help to know it's parameters

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