MATLAB: Merging two arrays based on index arrays

arrayMATLABmatrixmatrix array

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?

Best Answer

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