how to find the elements in a matrix that follow a certain pattern

5 ビュー (過去 30 日間)
Homayoon
Homayoon 2016 年 6 月 25 日
コメント済み: Walter Roberson 2016 年 6 月 25 日
Dear All,
I have been working on writing a code to get what I want and have not been luck yet. I hope you can help me to do so so that I can move on with my research. Any help will be appreciated.
I do have a column that has the following format in general:
[0;
0; % a number of zeros
.
.
5 %please note that the non-zero elements are essentially the row numbers i.e. the fifth element is 5 and so on.
6
7
8
0 % again a set of zeros
0
0
12
13
0
0]
what I want is to write a code that gives me the first and last element of each non-zero interval. for the example above my desired out put would be a matrix of 2*2 as
[5 8
12 13] % the first and second columns would be including the first and last non zero elements of each interval, respectively.
Thank you so much for your helps. I have been kind of stuck!

採用された回答

Star Strider
Star Strider 2016 年 6 月 25 日
This seems to work in the data you presented:
v = [0;
0;
0
5
6
7
8
0
0
0
12
13
0
0];
nzi = diff([0; v]);
nzigt0 = find(nzi > 1);
nzilt0 = find(nzi < 0);
Output = [v(nzigt0) v(nzilt0-1)]
Output =
5 8
12 13
  4 件のコメント
Homayoon
Homayoon 2016 年 6 月 25 日
yes and as I said, my friend your answer perfectly resolves my issue. Thanks for the time you devoted on helping me.
Star Strider
Star Strider 2016 年 6 月 25 日
As always, my pleasure!

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2016 年 6 月 25 日
編集済み: Andrei Bobrov 2016 年 6 月 25 日
v =[0
0
0
5
6
7
8
0
0
0
12
13
0
0];
z = [[0;v(1:end-1)],v];
out = z([0;diff(all(z,2))]==1,:);

Walter Roberson
Walter Roberson 2016 年 6 月 25 日
mask = logical(YourVector(:));
run_start = strfind([false; mask], [0; 1]);
run_end = strfind([mask; false], [1; 0]);
desired_matrix = [run_start(:), run_end(:)];
  3 件のコメント
Homayoon
Homayoon 2016 年 6 月 25 日
Error using strfind Input strings must have one row.
run_start = strfind([false; mask], [0; 1])
Walter Roberson
Walter Roberson 2016 年 6 月 25 日
mask = logical(YourVector(:)).';
run_start = strfind([false, mask], [0, 1]);
run_end = strfind([mask, false], [1, 0]);
desired_matrix = [run_start(:), run_end(:)];

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by