大家好,我遇到了一个问题。我将创建一个名为 quadrants 的函数,该函数将一个名为 n 的标量整数作为其输入参数。该函数返回 Q,一个 2n×2n 矩阵。Q 由四个 n×n 子矩阵组成。左上角子矩阵的元素都是1s,右上角子矩阵的元素是2s,左下角的元素是3s,右下角的元素是4s。
提前感谢您的帮助..
另一种方法是bsxfun
,reshape
和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
结果:
>> 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
由于 OP 对for
循环感到绝望,这里是另一种循环方法
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
结果:
>> quadrants(2)
ans =
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
我认为最简单的方法是(尽量避免matlab中的多个“for”循环,它不喜欢它们,尽量使用尽可能多的矩阵):
function[r] = Quadrant(n)
a = ones(n);
r = [a 2*a; 3*a 4*a];
end
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