改变数字排序/数字顺序
Alter number sort / number sequence
我有一个数组/数字序列 a=[1,2,3,4,5]
我正在尝试
创建一个数组/数字序列,如下所示 a_new
:
列 代表数字应该进入的顺序/索引。
a_new=...
[1,2,3,4,5;
2,1,2,3,4;
3,3,1,2,3;
4,4,4,1,2;
5,5,5,5,1]
我想在哪里使用 circshift
但很快发现那行不通。
a=[1,2,3,4,5];
for n=1:5
a_wrong(:,n)=circshift(a(:)',[0 n])(:)
end
产生
a_wrong=[
5 4 3 2 1
1 5 4 3 2
2 1 5 4 3
3 2 1 5 4
4 3 2 1 5]
有什么想法吗?如果那行不通,则不需要使用 circshift
。
PS:我正在使用类似于 Matlab 的 Octave 4.2
可能有很多不同的方法来生成这个矩阵。这是一个使用函数 repmat
, toeplitz
, tril
, and triu
:
>> a_new = tril(repmat(a.', 1, numel(a)), -1)+triu(toeplitz(a))
a_new =
1 2 3 4 5
2 1 2 3 4
3 3 1 2 3
4 4 4 1 2
5 5 5 5 1
我不确定是否有内置函数,但这应该可以;
a=[1,2,3,4,5];
a_out = ones(length(a), length(a))
for n=1:5
a_out(n,:) = [n*ones(n-1),a(n:end)]
end
我的电脑上没有安装 Octave 或 MATLAB,所以无法测试。这可能有一个愚蠢的错误,请原谅我!
您可以使用spdiags
生成矩阵:
n = numel(a);
a_new = spdiags([repmat(flip(a).',1,n); repmat(a,n-1,1)],(1-n):0);
我有一个数组/数字序列 a=[1,2,3,4,5]
我正在尝试
创建一个数组/数字序列,如下所示 a_new
:
列 代表数字应该进入的顺序/索引。
a_new=...
[1,2,3,4,5;
2,1,2,3,4;
3,3,1,2,3;
4,4,4,1,2;
5,5,5,5,1]
我想在哪里使用 circshift
但很快发现那行不通。
a=[1,2,3,4,5];
for n=1:5
a_wrong(:,n)=circshift(a(:)',[0 n])(:)
end
产生
a_wrong=[
5 4 3 2 1
1 5 4 3 2
2 1 5 4 3
3 2 1 5 4
4 3 2 1 5]
有什么想法吗?如果那行不通,则不需要使用 circshift
。
PS:我正在使用类似于 Matlab 的 Octave 4.2
可能有很多不同的方法来生成这个矩阵。这是一个使用函数 repmat
, toeplitz
, tril
, and triu
:
>> a_new = tril(repmat(a.', 1, numel(a)), -1)+triu(toeplitz(a))
a_new =
1 2 3 4 5
2 1 2 3 4
3 3 1 2 3
4 4 4 1 2
5 5 5 5 1
我不确定是否有内置函数,但这应该可以;
a=[1,2,3,4,5];
a_out = ones(length(a), length(a))
for n=1:5
a_out(n,:) = [n*ones(n-1),a(n:end)]
end
我的电脑上没有安装 Octave 或 MATLAB,所以无法测试。这可能有一个愚蠢的错误,请原谅我!
您可以使用spdiags
生成矩阵:
n = numel(a);
a_new = spdiags([repmat(flip(a).',1,n); repmat(a,n-1,1)],(1-n):0);