Reputation: 149
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..
Upvotes: 0
Views: 2357
Reputation: 11
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
Upvotes: 1
Reputation: 21
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
Upvotes: 1
Reputation: 3898
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
Upvotes: 1