如何制作一个以 n 作为参数的函数并在 matlab 中创建子矩阵
how to make a function that take n as argument and create submatrix in matlab
大家好,我陷入了 problem.i 我将创建一个名为 quadrants 的函数,该函数将一个名为 n 的标量整数作为其输入参数。函数 returns Q,一个 2n×2n 矩阵。 Q 由四个 n×n 子矩阵组成。左上角子矩阵的元素全为1,右上角子矩阵的元素为2,左下角的元素为3,右下角的元素为4。
在此先感谢您的帮助..
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
大家好,我陷入了 problem.i 我将创建一个名为 quadrants 的函数,该函数将一个名为 n 的标量整数作为其输入参数。函数 returns Q,一个 2n×2n 矩阵。 Q 由四个 n×n 子矩阵组成。左上角子矩阵的元素全为1,右上角子矩阵的元素为2,左下角的元素为3,右下角的元素为4。
在此先感谢您的帮助..
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