我有两个输入变量:
N=10;
M=4;
使用 Matlab,我想为任何 M 和 N 生成以下矩阵 - 不使用 for 循环:
%N = 1 2 3 4 5 6 7 8 9
Mat1 = [2, 3, 4, 5, 6, 7, 8, 9, 10; %M=1 -> Mat1(1, i) = N(i)+1
3, 6, 9, 12, 15, 18, 21, 27, 30; %M=2 -> Mat1(2, i) = N(i)+N(i)*2
4, 8, 12, 16, 20, 24, 28, 32, 36; %M=3 -> Mat1(2, i) = N(i)+N(i)*3
5, 10, 15, 20, 25, 30, 35, 40, 45] %M=4 -> Mat1(2, i) = N(i)+N(i)*4
%N = 1 2 3 4 5 6 7 8 9
Mat2 = [1, 2, 3, 4, 5, 6, 7, 8, 9; %M=1 -> Mat2(2, i) = N(i)
1, 4, 7, 10, 13, 16, 19, 25, 28; %M=2 -> Mat2(2, i) = N(i)+N(i)*2-2
1, 5, 9, 13, 17, 21, 25, 29, 33; %M=3 -> Mat2(2, i) = N(i)+N(i)*3-3
1, 6, 11, 16, 21, 26, 31, 36, 41] %M=4 -> Mat2(2, i) = N(i)+N(i)*4-4
一般说明:
% i=1:N %Mat1(M, i) = N(i)+N(i)*M , if M>1 % N(i)+1 , if M=1 %Mat2(M, i) = N(i)+N(i)*M-M , if M>1 % N(i) , if M=1
我写了一个带有两个for循环的代码,但是我想问一下是否有任何方法可以得到这些结果,而不使用循环。我尝试使用bsxfun
and arrayfun
,但没有得到正确的结果:
clear Mat1 Mat2
N=10;
M=9;
Mat1 = ones(M, N);
Mat2 = ones(M, N);
for i=1:M
for j=1:N
if i==1
Mat1(i, j) = j+1;
Mat2(i, j) = j;
elseif j ==1
Mat1(i, j) = j+j*i;
elseif i~=1 && j~=1
Mat1(i, j) = j+j*i;
Mat2(i, j) = j+j*i-i;
end
end
end
谢谢