0

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..

3 Answers3

1

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
Santhan Salai
  • 3,888
  • 19
  • 29
1

I think the simplest way to do it (try to avoid multiple "for" loops in matlab, it doesn't like them, try to use as much matrix as possible):

function[r] = Quadrant(n)
a = ones(n);
r = [a 2*a; 3*a 4*a];
end
Barry
  • 21
  • 4
1
 function [Q]=quadrant(n)
 W=zeros(n);
 X=ones (n);
Y= ones(n)*3;
Z= ones(n)*4;
V={[W], [X];
     [Y], [Z]}
Q=cell2mat(V)
end
Meidou
  • 11
  • 1
  • You should explain your code a bit rather than just posting the code. Thanks! – Will May 15 '15 at 04:45
  • This question already has a number of answers, including an accepted one, from over a week ago. You may want to clarify what your answer does, especially why it is better than those already posted. – APH May 15 '15 at 04:46