本文介绍了在octave/matlab中每隔n个位置在数组中插入项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在(a1)

示例:逻辑

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 插入后的 a1 如果 n = 3

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

a2 插入后的 new a1 如果 n = 2

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

a2 插入后的 a1 如果 n = 1

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

我尝试过

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

但是出现尺寸不匹配错误.

but I get dimensions mismatch error.

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

Please note this is just an example so I can't just calculate an answer I need to insert the data into the array. n is the starting position at which the array a2 is inserted into a1

推荐答案

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

First allocate an array of the combined size, then insert both original arrays to required indices. With a2 it is easy, you can just use n:n:end. To get indices for a1 you can subtract the set of a2 indices from the set of all indices:

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

这篇关于在octave/matlab中每隔n个位置在数组中插入项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 07:43