How do I find the indices of nonzero elements for a matrix of logical vectors?

10 次查看(过去 30 天)
For example, I have the following matrix with logical vectors as rows:
A=[1 0 0 0; 0 0 1 0; 0 0 0 1]
A = 3×4
1 0 0 0 0 0 1 0 0 0 0 1
I would like to get a vector with the indices of the first nonzero element for each row, such that the answer for matrix A should be:
v=[1;3;4]
v = 3×1
1 3 4
I'd be grateful for any tip how to do this. Thank you

采纳的回答

Matt J
Matt J 2022-3-8
A=[1 0 0 0; 0 0 1 0; 0 0 0 1];
[~,w]=max(A,[],2)
w = 3×1
1 3 4
  1 个评论
Distelfink
Distelfink 2022-3-8
Thank you! Yes, that works perfectly and is the general answer to finding the column indices of the first nonzero element per row - see also my related question, which also received that answer.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2022-3-5
Try find():
A=[1 0 0 0; 0 0 1 0; 0 0 0 1]
A = 3×4
1 0 0 0 0 0 1 0 0 0 0 1
[rows, columns] = find(A)
rows = 3×1
1 2 3
columns = 3×1
1 3 4
rows and columns are the (row, column) location of all the non-zero values in A.
  11 个评论
Distelfink
Distelfink 2022-3-8
Just a quick question to the respondents, since I am new to the forum: What is the best practice for me to make clear in this thread that my question was resolved? As I mentioned, I originally asked the question in an imprecise way and thus the answer I was looking for (Matt's answer in the comments above) was only posted in a comment to the answer above. Should I "accept" Image Analyst's answer nevertheless? Should I edit my original question and hint towards the comments of the answer? Thank you
Image Analyst
Image Analyst 2022-3-8
I'd ask Matt to post his answer as an official Answer. If he does, then you can Accept his answer and award him reputation points. If you learned anything from any of the other Answers in a post you can optionally "Vote" for them to award that poster reputation points also. You can only Accept one answer but you can vote for as many as you want.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by