MATLAB: Assigning element of another array into another array based on index

arrayassigning elementsindex

I've stored the index of the elements of interest in an array, B, and would like to use the values in B to obtain the values of the elements in another array, A, at positions indicated in B.
e.g.
A = [5 4 4 5 6 6 8 5 8 5 14 11 3 2 4 5];
B = [1 2 4 8 10 12 16];
for i = 1: length(B)
if (A(B(i))== 5)
idx = [idx,i];
end
end
form my understanding, i should be able to get idx = 1 4 8 10 16 However, what i am getting is idx = 1 5 10 15
I'm not sure what is the problem as the logic of the code seems right to me.
can i also check what is the difference between array and matrix?

Best Answer

You don't really need a loop at all and can do the whole thing in one line,
idx=B(A(B)==5)