Assigning element of another array into another array based on index

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?

 채택된 답변

Matt J
Matt J 2014년 10월 29일
편집: Matt J 2014년 10월 29일
You don't really need a loop at all and can do the whole thing in one line,
idx=B(A(B)==5)

댓글 수: 4

can i also check what is the difference between array and matrix?
Do you mean
difference = B-A(B)
i tried this, but i had an error that says index exceed matrix dimensions. Actually i dont get this line, i dont understand why should it be B(...)== 5 when im looking for the value inside A.
Matt J
Matt J 2014년 10월 29일
편집: Matt J 2014년 10월 29일
I never proposed anything that looks like B(...)== 5. The expression I wrote is B( A(B)==5 ).
I tested my proposal on your example data and it worked fine for me. So, whatever's causing your error, it's coming from something unposted.
Mich
Mich 2014년 10월 29일
편집: Mich 2014년 10월 29일
hey i apologise for my mistake. my original code was way more complex and i simplified it to this, but the same variables were used, thus resulting in my initial confusion when i tried out your suggestion. i tried your suggestion again and it works! thanks alot!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

vimala victor
vimala victor 2018년 5월 16일

0 개 추천

hi, i have one array RL=[1 13 11 14 25 37 53 29 75 81 66 10 98 15 33 44 77 88 20 49 1 3 4 2 5 1 2 2 3 4 2 1 5 2 3 1 2 4 3 3]; That is first row defines the index values and second row is the values of corresponding index.(Eg.for index value 1 the value is 1,index value 13 the value is 3...) and IM= 44 14 98 88 20 13 11 37 77 25 81 20; How can i extract the corresponding IM indexing Values from RL using indexing. please ,can anyone help me to clarify my doubt with how to define in matlab coding

댓글 수: 1

Please, start your own question rather than highjacking a very ancient one.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2014년 10월 29일

댓글:

2018년 5월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by