Search for a number pattern in an array

9 ビュー (過去 30 日間)
lightroman
lightroman 2017 年 11 月 13 日
コメント済み: lightroman 2017 年 11 月 13 日
Without using strfind is there a way to search for a pattern of less than 4 ones in a row? and if there are can i set them all to zero and track which set of 1s it is and record in another array. Example below, 'a' being original data, 'b' is the updated data, 'newArr' nth set of any amount of 1's that was replaced with zeros. Let me know if i need to further clarify. thanks!
if true
a = [0 0 0 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 0]
BECOMES
b = [0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0]
newArr = [2 4 5]
end
  2 件のコメント
Guillaume
Guillaume 2017 年 11 月 13 日
There are certainly many ways of doing it without strfind but what is the objection to using strfind if it fits the bill?
lightroman
lightroman 2017 年 11 月 13 日
im using octave which doesnt support it. I can get it working when using matlab at work, however, i only have octave at home. The same code errors. I use these forums because 99% of the time i dont have any problems between the two softwares.

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

採用された回答

the cyclist
the cyclist 2017 年 11 月 13 日
I recommend downloading the RunLength utility from the File Exchange.
Then the steps you'll need to take are
  • Identify the 1's in the first output
  • See if the run length is less than 4 using the second output
  • Calculate the indices you need using the third output
  2 件のコメント
Jan
Jan 2017 年 11 月 13 日
編集済み: Jan 2017 年 11 月 13 日
Explicitly:
a = [0 0 0 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 0];
[v, n] = RunLength(a);
isOne = (v == 1); % Location of ones
remove = isOne & (n < 4); % Less then 4 elements in a run
v(remove) = 0; % Set them to 0 in the output
b = RunLength(v, n)
posOne = cumsum(isOne); % The n.th run of ones
index = posOne(remove) % Select the removed runs only
@cyclist: It is surprising how often RunLength can solve problems in the forum. I have written it only for this purpose and did not use it ever for any of my own programming problems.
lightroman
lightroman 2017 年 11 月 13 日
thank you works perfectly.

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

その他の回答 (1 件)

Jan
Jan 2017 年 11 月 13 日
"Without using strfind"?! Why? Is this a homework? Then RunLength from the FileExchange might not be usable also. Then look in the code of RunLength_M to create your own efficient vectorized Run-Length method.
  1 件のコメント
lightroman
lightroman 2017 年 11 月 13 日
Nope, its for a personal project. I cant use strfind because I am using a particular version of octave which doesnt allow number patterns like matlab's strfind does.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by