search for a value in one matrix in another matrix

Hi everybody
Matrix A:
16 14 12 10 18
Matrix B:
2
3
5
4
1
new matrix :
2 14
3 12
5 18
4 10
1 16
For example, since 2 is written in matrix B, it prints the second row value in A next to 2 in the new matrix.
I need such a matrix. Could you help?
Thank u

 Accepted Answer

% Matrix A:
A = [16 14 12 10 18];
% Matrix B:
B = [2; 3; 5; 4; 1];
% new matrix :
new_matrix = [B A(B).']
new_matrix = 5×2
2 14 3 12 5 18 4 10 1 16

5 Comments

actually in my real problem the data is different. There are multiple rows in matrix A. And the number of columns in matrix A is more than the number of rows in matrix B. I guess that's why when I tried to implement yours it gave an error.
For example, the matrices are:
Matrix A:
16 14 12 10 18 15 11 19
17 14 12 18 11 10 12 16
Matrix B:
6 15
3 12
5 18
4 10
8 19
As you can see, 1.2 values are not used. Also I just got the values in matrix A from the first row.
My real life matrix is much larger. I wanted to explain this with a simple example.
Is such a solution possible?
@_'s code should also work for this case. You must have done something wrong in your code.
@Berfin Çetinkaya Do you mean like this? The difference here is that B is used to index into the first row of A.
% Matrix A:
A = [16 14 12 10 18 15 11 19; ...
17 14 12 18 11 10 12 16];
% Matrix B:
B = [6; 3; 5; 4; 8];
% new matrix
new_matrix = [B A(1,B).'] % using only first row of A now
new_matrix = 5×2
6 15 3 12 5 18 4 10 8 19
yes I meant that. Thanks a lot of.
Excellent. You're welcome!

Sign in to comment.

More Answers (0)

Categories

Tags

Asked:

on 29 Mar 2022

Commented:

on 30 Mar 2022

Community Treasure Hunt

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

Start Hunting!