Search code examples
matlabmatrixsubmatrix

how to make a function that take n as argument and create submatrix in matlab


hi everyone i stuck in a problem.i am going to make a function called quadrants that takes as its input argument a scalar integer named n. The function returns Q, a 2n-by-2n matrix. Q consists of four n-by-n submatrices. The elements of the submatrix in the top left corner are all 1s, the elements of the submatrix at the top right are 2s, the elements in the bottom left are 3s, and the elements in the bottom right are 4s.

thanks in advance for assistance..


Solution

  • One other approach with bsxfun, reshape and permute

    function [ out ] = quadrants( n )
    out = reshape(permute(reshape(bsxfun(@times,...
           ones(n,n,4),permute(1:4,[1 3 2])),n,2*n,[]),[1 3 2]),2*n,[]);
    end
    

    Results:

    >> quadrants(3)
    
    ans =
    
     1     1     1     2     2     2
     1     1     1     2     2     2
     1     1     1     2     2     2
     3     3     3     4     4     4
     3     3     3     4     4     4
     3     3     3     4     4     4
    

    As the OP is desperate with for loop here is an alternate loopy approach

    function [ out ] = quadrants( n )
    out(2*n,2*n) = 0;
    count = 1;
    for ii = 1:n:2*n
        for jj = 1:n:2*n
            out(ii:ii+n-1,jj:jj+n-1) = count;
            count = count + 1;
        end
    end
    end
    

    Results:

    >> quadrants(2)
    
    ans =
    
     1     1     2     2
     1     1     2     2
     3     3     4     4
     3     3     4     4