MATLAB Answers

How to campare index number of a matrix with other

2 views (last 30 days)
Ass
Ass on 15 Apr 2019
Commented: Ass on 15 Apr 2019
I have two array. A=[ 9 8 5 4 4 10] and B=[1 1 1 3 3 3 2 2 1 1]. Now, I want to campare A and B. The index number of each element in matrix B is same in matrix A. I want to represent the matrix A by the value of matrix B as its index number is same with. Now I want to represent matrix A as like B i.e. A will be A=[1 2 3 3 3 1]. How will write it code.

  0 Comments

Sign in to comment.

Accepted Answer

Raj
Raj on 15 Apr 2019
for i=1:numel(A)
A(i)=B(A(i));
end
Also please see this.

  6 Comments

Show 3 older comments
Rik
Rik on 15 Apr 2019
I think it is better to learn complex syntax with small examples. Especially for new users it is important to not resort to loops. Here it is easy to see how to avoid loops, so pausing to consider how to avoid a loop is a useful exercise. Learn it when it doesn't matter so you can apply it when it does.
Stephen Cobeldick
Stephen Cobeldick on 15 Apr 2019
"...the 'for loop' code gives a better understanding of what is happening in the background.
I disagree: MATLAB is a high-level language and array indexing is one of its most powerful features. Learning how to use array indexing is not more complex than a loop: Riks solution is simpler than this answer and more efficient.
Array indexing is required for any user who wants to learn how to use MATLAB effectively.

Sign in to comment.

More Answers (1)

Rik
Rik on 15 Apr 2019
A=[ 9 8 5 4 4 10];
B=[1 1 1 3 3 3 2 2 1 1];
newA=B(A);

Tags

Community Treasure Hunt

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

Start Hunting!