【问题标题】:Inserting items in an array every nth place in octave / matlab在八度/ matlab中每隔n个位置插入一个数组中的项目
【发布时间】:2016-09-08 20:11:57
【问题描述】:

如何在数组 (a2) 中的每个 (a1)

中的每个 nth 位置插入元素

示例:逻辑

a1 = [1,10,2,20,3,30,4,40,5,50];
a2 = [100,200,300,400,500];
n=3 % n would be the position to place the elements found in (a2) every **nth** position in (a1).  
*n is the starting position at which the array a2 is inserted into a1*

插入 a2 后的 new a1 if n=3 看起来像

a1 = [1,10,100,2,20,200,3,30,300,4,40,400,5,50,500];

插入 a2 后的 new a1 if n=2 看起来像

a1 = [1,100,10,2,200,20,3,300,30,4,400,40,5,500,50];

new a1 if n=1 在插入 a2 后看起来像

a1 = [100,1,10,200,2,20,300,3,30,400,4,40,500,5,50];

我试过了

a1(1:3:end,:) = a2;

但我收到尺寸不匹配错误。

请注意,这只是一个示例,因此我不能只计算答案我需要将数据插入到数组中。 n 是数组 a2 插入 a1

的起始位置

【问题讨论】:

  • 从您的示例中,您似乎没有在每个nth 位置插入a2 的元素,而是在每个3rd 位置插入它们,从位置n 开始.这就是你想要达到的目标吗?
  • @beaker 是的,在这种情况下你是对的
  • "in this instance" 暗示其他实例的行为不同。除非您告诉我们在所有情况下应该采取什么行为,否则我认为没有人可以帮助您。

标签: arrays matlab octave


【解决方案1】:

另一种选择是使用 circshift 将您想要的行移到顶部

orig_array=[1:5;10:10:50;100:100:500;1000:1000:5000];
row_on_top=3 %row to be on top

[a1_rows a1_cols]=size(orig_array)
a1 = circshift(orig_array, [-mod(row_on_top,a1_rows)+1, 0])
Anew = zeros(1,a1_rows*a1_cols)
for n=1:1:a1_rows
  n
  insert_idx=[n:a1_rows:a1_cols*a1_rows]  %create insert idx
  Anew(insert_idx(1:a1_cols))=a1(n,:) %insert only 1:a1_cols values

end
Anew=Anew(:)

【讨论】:

    【解决方案2】:

    首先分配一个组合大小的数组,然后将两个原始数组插入所需的索引。使用a2 很简单,您只需使用n:n:end。要获取 a1 的索引,您可以从所有索引集中减去 a2 索引集:

    a1 = [1,10,2,20,3,30,4,40,5,50];
    a2 = [100,200,300,400,500];
    n = 3;
    
    res = zeros(1,length(a1)+length(a2));
    res(n:n:n*length(a2)) = a2;
    a1Ind = setdiff(1:length(res), n:n:n*length(a2));
    res(a1Ind) = a1;
    
    >> res
    res =
         1    10   100     2    20   200     3    30   300     4    40   400     5    50   500
    

    【讨论】:

    • 谢谢,但是当我将您的 n 值更改为 n=2 或 n=1 时,我收到一个错误“错误:A(I) = X: X 必须与我的大小相同”它看起来好像它不适用于第 N 名 1 或 2
    • 好的,编辑答案使其更通用。您只需要限制a2 索引的集合。
    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多