array indexing with repeated index, index size larger than the array

1 view (last 30 days)
Hi
I want to do c = 1; for i = I B(c) = A(i); c = c + 1; end
where I is a vector.
For instance A = [a b c d]; I = [1 1 3 1 1 1 2 2 1]; then B = [a a c a a a b b a];
is there a fast way to do this without for loop?
Thanks

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 29 Aug 2018
One way:
A = {'a' 'b' 'c' 'd'};
I = [1 1 3 1 1 1 2 2 1];
B = A(I);
  5 Comments
Stephen23
Stephen23 on 30 Aug 2018
Edited: Stephen23 on 30 Aug 2018
@Sung-En Chiu: sure, using basic MATLAB indexing. Just use the code given in Andrei Bobrov's answer:
C = A(I)
Sung-En Chiu
Sung-En Chiu on 30 Aug 2018
oh, I see. I read his code wrong. Didn't know that can create a larger matrix by this indexing before. tks

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!