how to find the column number of first zero element of each row

12 ビュー (過去 30 日間)
Jason
Jason 2016 年 2 月 19 日
編集済み: Sunetra CV 2019 年 11 月 14 日
Hi,all. could you please tell me how to find the column number of first zero element of each row. eg. for the matrix in the picture, I want the output will be outputmatrix=[3;4;4;5;5;6;6;6;6;6;1;1;1;1;1]. Thank you!

採用された回答

MHN
MHN 2016 年 2 月 19 日
編集済み: MHN 2016 年 2 月 19 日
This is your answer:
a =[ -1 3 0 0 0 0
2 3 4 5 0 0
1 2 1 0 0 0]
b = abs(a); % it is a trick which forces min to do not consider your negative numbers as minimum
[~,ind] = min(b')
  2 件のコメント
MHN
MHN 2016 年 2 月 19 日
編集済み: MHN 2016 年 2 月 19 日
So, for your matrix it is just one line code:
[~,ind] = (min((abs(SumofSet1))'))
Jason
Jason 2016 年 2 月 19 日
thank you very much!

サインインしてコメントする。

その他の回答 (2 件)

Adam
Adam 2016 年 2 月 19 日
編集済み: Adam 2016 年 2 月 19 日
sum( abs( cumprod( yourMatrix, 2 ) ) > 0, 2 ) + 1;
should work I think. I tested in on a small matrix I made and it seems to give the correct answer. There may be simpler methods though!
The logic behind it is as follows:
  • cumprod is the cumulative product, run along each row (dimension 2) which will always be 0 for values after the first 0, hence the result of this will be a matrix in which only the elements before the first 0 on a row will be non-zero.
  • abs will ensure that all non-zero elements are positive in order for the following check to work correctly.
  • taking the sum of all the elements greater than 0 will give you the index of the last non-zero element.
  • Adding 1 at the end will give the element of the first 0 which should always be the column immediately after the last non-zero.
If need be you can use a small tolerance e.g. 1e-6 to hard set elements below that absolute tolerance to 0 before doing this as values that are not precisely 0 will likely cause problems.
  2 件のコメント
Jason
Jason 2016 年 2 月 19 日
Thank you,but the result is not the same as i wanted. I didn't understand why you use 'sum' function here. because the element in matrix is very small, use 'cumsum' may cause the inaccuracy of the results.
Walter Roberson
Walter Roberson 2016 年 2 月 19 日
sum(cumprod(~YourMatrix, 2), 2) + 1
Note: this will be incorrect / misleading for any row for which there is no 0 (in which case no desired result has been defined by the poster)

サインインしてコメントする。


Sunetra CV
Sunetra CV 2019 年 11 月 14 日
編集済み: Sunetra CV 2019 年 11 月 14 日
will this work if all the elements of my matrix are decimals?

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by