Matlab:通过置换重塑向量?
Matlab: reshape a vector by permuting?
我有以下向量 u
:
u=[a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4];
我想置换 u
的元素以生成以下向量,uNew
:
uNew=[a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4];
除了 for 循环,我想不出其他办法:
uNew=[];
for i=1:4
uNew=[uNew,u(i:4:end)];
end
但我希望内置函数存在?谢谢!
将其重塑为矩阵,逐列读取,包含您想要的顺序:
n=3 % number of categories (a,b,c)
u2=reshape(u,[],n).'
然后将其转换回向量:
u2=u2(:);
我会使用 。但只是提供一个替代方案:
m = 4; %// size of each initial "block"
[~, ind] = sort(mod(0:numel(u)-1,m)+1);
uNew = u(ind);
请注意,这是有效的,因为根据 sort
's documentation,
The ordering of the elements in B (output) preserves the order of any equal elements in A (input)
另一种方法:
N = 4;
uNew = u(mod(0:numel(u)-1, N) * N + floor((0:numel(u)-1)/N) + 1);
我有以下向量 u
:
u=[a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4];
我想置换 u
的元素以生成以下向量,uNew
:
uNew=[a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4];
除了 for 循环,我想不出其他办法:
uNew=[];
for i=1:4
uNew=[uNew,u(i:4:end)];
end
但我希望内置函数存在?谢谢!
将其重塑为矩阵,逐列读取,包含您想要的顺序:
n=3 % number of categories (a,b,c)
u2=reshape(u,[],n).'
然后将其转换回向量:
u2=u2(:);
我会使用
m = 4; %// size of each initial "block"
[~, ind] = sort(mod(0:numel(u)-1,m)+1);
uNew = u(ind);
请注意,这是有效的,因为根据 sort
's documentation,
The ordering of the elements in B (output) preserves the order of any equal elements in A (input)
另一种方法:
N = 4;
uNew = u(mod(0:numel(u)-1, N) * N + floor((0:numel(u)-1)/N) + 1);