【问题标题】:Rearrange vector every nth column每隔 n 列重新排列向量
【发布时间】:2018-01-30 07:41:02
【问题描述】:

假设我有一个向量:

A=[1 2 3 6 7 8 11 12 13]

我正在尝试实现最终输出,例如:

[1 6 11 2 7 12 3 8 13]

向量重新排列到每第 n 列的前面,在本例中为第 3 列。使用索引会起作用,但它需要一个循环,我试图避免这种循环。知道如何以矢量化方式进行操作吗?谢谢!

nth=3;
for i=1:nth:size(A,2)
    A_(:,nth)= A(:,i:nth:end)
end

【问题讨论】:

  • 假设A 的长度可以被3 整除,那么reshape(reshape(A,3,[]).',1,[]) 应该可以工作。
  • @jodag,要将其推广到问题中的第 n 列,只需将 3 替换为 n

标签: matlab vector


【解决方案1】:

@jodag 在 cmets 中发布的建议非常有效。或者,这也应该可以完成工作......但约束是相同的,A 必须能被nth 整除:

nth = 3;
A = [1 2 3 6 7 8 11 12 13];
A_len = numel(A);
A_div = floor(A_len / nth);

seq = repmat(1:nth:A_len,1,A_div);
inc = sort(repmat(0:nth-1,1,A_div));

A = A(seq + inc)

输出:

A =
     1     6    11     2     7    12     3     8    13

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多