find and print values ​​from matrix

Hello everyone ,
works: 1 2 3 4 5 6
A1 3 1 2 2 3 1
A2 2 3 3 1 2 3
Can I find the value 2 in each row in the matrix given above and print the job number in another matrix?
Example: I found 2 values in row A1 in the given matrix. These are the 3rd and 4th jobs. I need to print these jobs in a matrix like below.
Works: 2
3
4

 Accepted Answer

% given matrix with three rows:
M = [ ...
1 2 3 4 5 6; ...
3 1 2 2 3 1; ...
2 3 3 1 2 3];
% value to look for in the second row of M:
val = 2;
% find the indices where val is in the second row of M:
idx = find(M(2,:) == val);
% output is val followed by those indices, all together in a column vector:
output = [val; idx(:)]
output = 3×1
2 3 4

4 Comments

Hello again;
Works: 5 8 9 15 7 12
A1: 1 3 2 3 1 2
A2: 3 2 1 1 2 3
Looking at the matrix structure given above, I want to print jobs with the value 3 in row A1 in another matrix. how can I do it?
Example for A1 ;
new matrix: 8
15
Works = [5 8 9 15 7 12];
A1 = [1 3 2 3 1 2];
A2 = [3 2 1 1 2 3];
result = Works(A1 == 3).'
result = 2×1
8 15
This uses what is called logical indexing:
If Works, A1 and A2 are rows of a matrix, it works the same but you have to specify the row number instead of referring to the different variables:
M = [5 8 9 15 7 12; ...
1 3 2 3 1 2; ...
3 2 1 1 2 3];
result = M(1,M(2,:) == 3).'
% ^^^^^^ result is ...
% ^^^^ elements from row 1 of M ...
% ^^^^^^ where row 2 of M ...
% ^^^^ is 3
You're welcome!

Sign in to comment.

More Answers (0)

Products

Release

R2021a

Asked:

on 28 Mar 2022

Commented:

on 29 Mar 2022

Community Treasure Hunt

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

Start Hunting!