Inserting items in an array every nth place in octave / matlab

强颜欢笑 提交于 2019-12-25 06:59:20

问题


How can I insert elements in an array (a2) every nth place in (a1)

Example: Logic

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*

The new a1 if n=3 after inserting a2 into it would look like

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

The new a1 if n=2 after inserting a2 into it would look like

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

The new a1 if n=1 after inserting a2 into it would look like

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

I tried

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

but I get dimensions mismatch error.

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


回答1:


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



回答2:


Another option is to use circshift to shift the row you want on top

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(:)


来源:https://stackoverflow.com/questions/37196296/inserting-items-in-an-array-every-nth-place-in-octave-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!