amusing
amusing

Reputation: 41

How to insert elements according to array of indices in MATLAB?

Say, I have Index array I = [2 4 6] Another, array A =[1 0 0] I want to insert elements of array A in array C at position 2 , 4 and 6.

Array C is initially empty.

Run 2: I = [1, 7, 8] A = [0 0 1] I would want to insert elements of array A in array C at position 1 , 7 and 8.

And, so on.

Please help. Thanks.

Upvotes: 0

Views: 69

Answers (1)

rayryeng
rayryeng

Reputation: 104464

Cheery essentially answered the question for you, but in order to be complete, simply use the array I and index into C and use I to place the values of A into the corresponding slots in C. As such:

C(I) = A;

If C was not already allocated, then C will pad whatever you didn't index with zeroes. As such, given your two examples, this is what we get:

I1 = [2 4 6];
I2 = [1 7 8];
A1 = [1 0 0];
A2 = [0 0 1];
C1(I1) = A1
C2(I2) = A2


C1 =

     0     1     0     0     0     0   

C2 =

     0     0     0     0     0     0     0     1

However, because your array A already has zeroes, you can't really see the effect of this type of assignment. If you change up your array A into some other values that don't include zero, then you'll see that this does work.

Upvotes: 1

Related Questions