How to identify a specific location within a matrix based on a value

3 views (last 30 days)
Hi,
I have a matrix of all 0s and 1s. I'd like to identify the exact location of the first nonzero value of each row. I've found several different ways to identify the nonzero value (e.g., find()) but I don't need to know the value (I know it's 1), I need to know it's precise location.
I'm working on a program that will identify the first nonzero value in each row and compare those locations to another matrix and eventually I would like to shift matrix 2 to match the first nonzero values in matrix 1.
Any help with identifying the location of a specific value in a row (in this case the first nonzero value) is greatly appreciated.
Thanks.

Accepted Answer

yonatan gerufi
yonatan gerufi on 8 Sep 2014
Edited: yonatan gerufi on 8 Sep 2014
possible solution:
% construct random binary matrix
a=round(rand(5,10));
% find first minimal value:
[value,position] = max(a,[],2)
now 'position' will contain the position of first maximum element in a row.
'value' will contain this element value.
unless all the line is 0's (you should check it at 'value') 'position' will give you the first one!
if you have any more ways please post them.
good luck!
  3 Comments
Tricia
Tricia on 8 Sep 2014
I do have one follow up question actually. I'm having trouble returning the 'value' results into a new array. I'd like to save the column positions as a completely new array, if that's possible. Do you know if it is?
Thanks again!

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!