2016-05-12 62 views
0

我怎樣才能插入元件以陣列(A2)第n發生在(a1)中插入項目在一個陣列中的八度每第n個位置/ MATLAB

實施例:邏輯

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* 

A1如果n = 3的插入 A2 到它看起來像

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

A1如果n = 2的插入A2進去後看起來像

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

A1如果n = 1插入後A2到它看起來像

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

我試圖

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

,但我得到的尺寸不匹配錯誤。

請注意這只是一個例子,所以我不能只是計算一個答案我需要將數據插入到數組Ñ是所述陣列A2插入A1

+0

從你的例子中,你似乎並沒有在每個'第n'位置插入'a2'的元素,而是將它們插入到每個'3rd'位置,以'n'開始。那是你想要達到的目標嗎? – beaker

+0

@beaker在這種情況下,您是正確的 –

+0

「在此實例中」意味着其他實例的行爲不同。除非你告訴我們所有情況下的行爲,我認爲任何人都無法幫助你。 – beaker

回答

1

首先分配的組合尺寸的陣列,然後插入兩個原始陣列所需的索引的開始位置。用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 
+0

謝謝,但是當我將n的值更改爲n = 2或n = 1時,出現錯誤「錯誤:A(I)= X:X必須與我具有相同的大小」,看起來它不起作用第N個地方1或2 –

+0

好的,編輯答案使其更通用。你只需要限制一組'a2'指數。 –

0

另一種選擇是使用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(:) 
相關問題