一つの行をグループ分けすることはできますか?

6 views (last 30 days)
KO
KO on 11 May 2021
Edited: Atsushi Ueno on 12 May 2021
ある1×1行のlogical配列,例えば
000111110011110001111
を0,1で振り分けて以下のように1×6セル配列などにグループ分けすることはできますか?
{000}{11111}{00}{1111}{000}{1111}

Accepted Answer

Atsushi Ueno
Atsushi Ueno on 12 May 2021
Edited: Atsushi Ueno on 12 May 2021
こんなんでどうでしょう
a = logical([0 0 0 1 1 1 1 1 0 0 1 1 1 1 0 0 0 1 1 1 1]);
idx = find([diff(a) numel(a)]); %境目のインデックス
width = diff([0 idx]); %各要素グループのサイズ(幅)
b = mat2cell(a, 1, width); %1行width列に分割し1×6セル配列に束ねる
a = 1×21 の logical 配列
0 0 0 1 1 1 1 1 0 0 1 1 1 1 0 0 0 1 1 1 1
idx = 3 8 10 14 17 21
width = 3 5 2 4 3 4
b = 1×6 の cell 配列
[1×3 logical] [1×5 logical] [1×2 logical] [1×4 logical] [1×3 logical] [1×4 logical]

More Answers (1)

Kojiro Saito
Kojiro Saito on 12 May 2021
きれいなやり方ではなく、愚直にfor文を使った方法ですが、下記で実現できます。
resultにグループ分けされたセル配列が格納されます。
line = '000111110011110001111';
tmpStr = line(1);
count = 1;
idx = 1;
for n=2:length(line)
% n番目の文字と1つ前の文字を比較し、違ったらresultに文字を格納
if ~strcmp(line(n), tmpStr)
result{count} = line(idx:n-1);
count = count+1;
idx = n;
end
% nが最後の場合はresultに文字を格納
if n == length(line)
result{count} = line(idx:n);
end
% 次のループのために文字を保持
tmpStr = line(n);
end

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!