答案 0 :(得分:5)
这是使用逻辑索引的方法:
n = 4;
A = nan(n);
A(~eye(n)) = 1:n^2-n; %// Only replace values *not* on diagonal
A = A.'
A =
NaN 1 2 3
4 NaN 5 6
7 8 NaN 9
10 11 12 NaN
答案 1 :(得分:3)
n = 4;
A = reshape(1:n*(n-1),n-1,n).';
z = zeros(n,1);
A = [tril(A,-1) z]+[z triu(A)]+diag(NaN(n,1));
,在这种情况下,对于4乘4矩阵,返回
A =
NaN 1 2 3
4 NaN 5 6
7 8 NaN 9
10 11 12 NaN
这是另一种使用reshape
的方式:
n = 4;
A = [reshape(1:n*(n-1),n,n-1);NaN(1,n-1)];
A = reshape([NaN;A(:)],n,n).'
答案 2 :(得分:3)
这是另一种方式:
n = 4; %// matrix size
x = 1-eye(n);
x(:) = cumsum(x(:));
x = x.' + diag(NaN(1,n));
答案 3 :(得分:2)
您可以从nan
矩阵开始,找到对角线的线性索引,然后用递增的范围填充其余元素:
n=4;
A=nan(n);
inds=setdiff(1:n^2,sub2ind([n,n],1:n,1:n));
A(inds)=1:numel(inds);
A=A.'; %' transpose to get the matrix we need
最后的转置是必要的,因为线性索引将列优先,但您的细节需要行首先分配矩阵元素。
结果:
>> A
A =
NaN 1 2 3
4 NaN 5 6
7 8 NaN 9
10 11 12 NaN