Merging two arrays based on index arrays

Illustration
Mauricio - 2020-11-04T09:37:13+00:00
Question: Merging two arrays based on index arrays

I have the  arrays z_index = [2 3] and y_index = [4 1 5]. They store the indices of a main array x. z(z_index) = [1 3] and y(y_index) = [-2 4 2]. How do I code to find the array x = [4 1 3 -2 2] which merges the z and y arrays based on the index arrays z_index and y_index?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

z_index = [2,3];
y_index = [4,1,5];
z(z_index) = [1,3];
y(y_index) = [-2,4,2];

x(z_index) = z(z_index); % RHS = [1,3]
x(y_index) = y(y_index)  % RHS = [-2,4,2]
 
x = 1×5
     4     1     3    -2     2
Or slightly more robustly:
 
x = [z(z_index),y(y_index)]; % RHS = [1,3,-2,4,2]
x([z_index,y_index]) = x
x = 1×5
     4     1     3    -2     2


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!