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

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

One way:
A = {'a' 'b' 'c' 'd'};
I = [1 1 3 1 1 1 2 2 1];
B = A(I);

5 Comments

tks, did a small test the speed seems to be slower than the for loop
len = 10000000;
A = [10 5 4 1 2];
I = randi(5,1,len);
B = zeros(1,len);
C = zeros(1,len);
tic();
tmpA = num2cell(A);
B = tmpA(I);
%B = cell2mat(B);
toc();
tic();
for i = 1:len
C(i) = A(I(i));
end
toc();
with the conversion cell2mat it is
Elapsed time is 6.572784 seconds.
Elapsed time is 0.137823 seconds.
without conversion back still
Elapsed time is 0.093561 seconds.
Elapsed time is 0.093041 seconds.
The conversion cell2mat takes a lot of memory for some reason
this is test over Matlab 2018a
is there other way or this for loop actually not to bad?
@Sung-En Chiu: why do you use num2cell and cell2mat? Indexing is a very basic (and efficient) MATLAB operation, it works perfectly on numeric arrays, just as the introductory tutorials show:
@Sung-En Chiu: sure, using basic MATLAB indexing. Just use the code given in Andrei Bobrov's answer:
C = A(I)
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!