0

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

Rick T
  • 3,349
  • 10
  • 54
  • 119
  • From your examples, it seems that you're not inserting the elements of `a2` at every `nth` position, you're inserting them at every `3rd` position starting with position `n`. Is that what you're trying to achieve? – beaker May 13 '16 at 01:48
  • @beaker Yes in this instance you are correct – Rick T May 13 '16 at 02:34
  • "in this instance" implies that other instances behave differently. Unless you tell us what the behavior should be in all instances, I don't think anyone can help you. – beaker May 13 '16 at 14:27

2 Answers2

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
nirvana-msu
  • 3,877
  • 2
  • 19
  • 28
  • thanks but when I change your value of n to n=2 or n=1 I get an error "error: A(I) = X: X must have the same size as I" it looks like it doesn't work for Nth place 1 or 2 – Rick T May 12 '16 at 20:57
  • Ok, edited the answer to make it more generic. You just had to limit the set of `a2` indices. – nirvana-msu May 12 '16 at 21:01
0

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(:)
Rick T
  • 3,349
  • 10
  • 54
  • 119