Search code examples
matlabmatrixreplacelist-manipulation

How to replace a block matrix with a new one?


I have an image size 128*128, I divided into 32*32 non-overlapping blocks, the problem is that I want to change the values of a specific or choosing block (the first or the 3rd.. for example) and getting a block with new values then replace it in my image. Do you have any idea how to get an image with ONE block modified ( NOT all of them)? Thank you This is an example with a small matrix

    %*********************
    A=magic(6)  ;      %%%%% matrix size 6*6
    B=Block(A,2,2) ;    % divide the matrix into 2*2 non-overlapping blocks
    subblock=B{3}  ;    % Choose the 3rd block
    new_block= 2*subblock; % change the block values by multipliying by 2

This is what I get

A = 35     1     6    26    19    24
     3    32     7    21    23    25
    31     9     2    22    27    20
     8    28    33    17    10    15
    30     5    34    12    14    16
     4    36    29    13    18    11

I extract the 3rd block

  sub_block=19    24
            23    25

Now I multiplied by 2 :

    new_block=  38    48
                46    50

This is my Block function:

    function A=Block(IM,p,q)  
     p=3;
     q=3;
     [m,n] = size(IM);
     IJ = zeros(p,q);
     z = 1;
     for m1 = 1:m/p   
     for n1 = 1:n/q  
     if m1*p <= m;
     if n1*q <= n;

      for i = (m1-1)*p+1:m1*p
         for j = (n1-1)*q+1:n1*q
             IJ(i-(m1-1)*p,j-(n1-1)*q) = IM(i,j);
           if (i-(m1-1)*p)==p&&(j-(n1-1)*q)==q;
               OUT = IJ;
              A{1,z} = OUT;
              z = z+1;
           end
         end
      end
    end
   end
end

end I want to replace these values in matrix A , but depending on block number. How can I do it?


Solution

  • Just type in the rows and cols you want to access, for your example

    A(1:2,5:6)=A(1:2,5:6)*2
    

    more generic, where n is the nth column block and m is the mth row block and c is the block width and r is the block height (in your example, n = 3, m = 1, r=c=2)

    A(((m-1)*r+1):(m*r), ((n-1)*c+1):(n*c)) = any block of size(r,c)