Reputation: 1492
Consider the following example
A =
6 9 4 7 10
3 6 5 5 9
10 4 9 8 6
10 6 3 4 6
6 3 3 8 6
6 4 4 4 5
5 10 8 5 7
10 10 8 8 7
5 7 8 9 9
3 3 6 3 9
[~,Inx] =max(A, [],2)
Inx =
5
5
1
1
4
1
2
1
4
5
The above code returns index of the maximum number along each column like in first row the max number is 10 in 5th row so Inx(1) = 5
Can we do the same thing for find ? like for example if I want to find a specific number in each row lets say 8
>> find(A == 8)
ans =
27
28
29
33
35
38
I will get the indices but not row wise like we get for the max()
is there some way to do minipulate find to get that ? or else some other way
Update : I know we can use [row,col,v] = find(___)
but there is one problem with that it only returns for the rows where the value is present
Upvotes: 1
Views: 94
Reputation: 65430
You can simply convert A
to a logical matrix where it's 1
if equal to 8
and 0
otherwise. Then you can use the second output of max
to find the column which contains the first 8
in each row. If a row doesn't contain any 8
's the first output of max
will be a 0
and the second output will be 1
.
You can multiply the first and second outputs to zero-out these rows that didn't have an 8
.
[has8, col] = max(A == 8, [], 2);
% Zero out any rows that didn't contain an 8
result = has8 .* col;
% 0
% 0
% 4
% 0
% 4
% 0
% 3
% 3
% 3
% 0
If you'd rather have NaN
's than 0
's, you could do the following which exploits the fact that 0/0 == NaN
result = has8 .* col ./ has8;
% NaN
% NaN
% 4
% NaN
% 4
% NaN
% 3
% 3
% 3
% NaN
Upvotes: 3
Reputation: 809
Inx = zeros(size(A,1),1); % initialize with default values
[row,col,v] = find(A==8); % find the proper indices
Inx(row) = col; % insert values
Upvotes: 0