Matlab Find() Function

5 ビュー (過去 30 日間)
Yahia Gebril
Yahia Gebril 2022 年 3 月 13 日
コメント済み: Image Analyst 2022 年 3 月 14 日
Hello, I have a matrix -
M = [−1 −1 0 0 ; 1 0 −1 0 ; 0 1 1 −1; 0 0 0 1 ; 1 −1 0 0 ]
Basically I have to go along the first row and find an element value of "-1", then look along the columns which the value "-1" was found and look for value "1". I have then to sum the row index of the column which the value "1" was found. (Loop of sorts) until I've reached the end.
Hope that makes sense and thanks
  3 件のコメント
Image Analyst
Image Analyst 2022 年 3 月 13 日
Is there always a 1 directly below the "first -1 after a 1"?
Did you try a simple for loop?
Yahia Gebril
Yahia Gebril 2022 年 3 月 14 日
Yeah so u go from -1 to 1 then to -1. This is what i have so far, what do you think? Also how would the For loop work?

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

回答 (1 件)

Image Analyst
Image Analyst 2022 年 3 月 13 日
Do you mean like this:
M = [-1 -1 0 0 ; 1 0 -1 0 ; 0 1 1 -1; 0 0 0 1 ; 1 -1 0 0 ]
[rows, columns] = size(M)
output = zeros(rows, 2); % List of starting column and ending column for every row.
col1 = find(M(1, :) == -1, 1, 'first');
output(1, 1) = col1;
for row = 2 : rows
col2 = col1 - 1 + find(M(row, col1 : end) == -1, 1, 'first');
if isempty(col2)
% No more results found. Reached last column of array.
break;
end
% Save results
output(row, 1) = col1;
output(row, 2) = col2;
col1 = col2;
end
output
Not sure why you're wanting the last 1 in row 4 since there is no -1 that follows it.
  2 件のコメント
Yahia Gebril
Yahia Gebril 2022 年 3 月 14 日
That looks pretty solid, however for the output, I have to keep a sum of the row position that the number "1" is found. For example, in the matrix given previously, it would be D=1+3+4=8. But the answer given is great man, thank you so much for your time.
.
Image Analyst
Image Analyst 2022 年 3 月 14 日
You can use cumsum() or sum() at the end to sum up all the individual indexes.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by