Merging two arrays based on index arrays

M
Mauricio · Nov 4, 2020 · 1.9K views
Question
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 PhD Expert
Answered Aug 14, 2026
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
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!