Can I arrange a double array into cell array based on discontinuity of values?

1 回表示 (過去 30 日間)
Josh Hwa
Josh Hwa 2019 年 4 月 28 日
コメント済み: Dyuman Joshi 2023 年 12 月 14 日
I have 1x15 double array defined as 'a' and I would like to make them classified into each cell column if the increment of value is broken. This is my code, I have no idea how to make a1 become a2. If the next value is not the prvious number, n+1, then it should break and create new cell column.
axis([0 30 0 30]);
hold on;
a1=[1 2 3 4 5 10 11 12 13 18 19 20 21 22 23];
a2={[1 2 3 4 5] [10 11 12 13] [18 19 20 21 22 23]} ;
cellfun(@(x) plot(x,x), a2);
The length is not fixed, it could be like this
a1=[1 2 3 4 5 6 7 8 9 10 11 12 13 18 19 20 21 22 23];
a2={[1 2 3 4 5 6 7 8 9 10 11 12 13] [18 19 20 21 22 23]} ;
or like this.
a1=[1 2 3 4 11 12 13 18 19 20 21 22 23 30 31 32 33 40 41 42];
a2={[1 2 3 4] [11 12 13] [18 19 20 21 22 23] [30 31 32 33] [40 41 42]};

回答 (1 件)

Voss
Voss 2023 年 12 月 14 日
a1=[1 2 3 4 5 10 11 12 13 18 19 20 21 22 23];
a2 = split_vector(a1)
a2 = 1×3 cell array
{[1 2 3 4 5]} {[10 11 12 13]} {[18 19 20 21 22 23]}
a1=[1 2 3 4 5 6 7 8 9 10 11 12 13 18 19 20 21 22 23];
a2 = split_vector(a1)
a2 = 1×2 cell array
{[1 2 3 4 5 6 7 8 9 10 11 12 13]} {[18 19 20 21 22 23]}
a1=[1 2 3 4 11 12 13 18 19 20 21 22 23 30 31 32 33 40 41 42];
a2 = split_vector(a1)
a2 = 1×5 cell array
{[1 2 3 4]} {[11 12 13]} {[18 19 20 21 22 23]} {[30 31 32 33]} {[40 41 42]}
function out = split_vector(a)
d = diff(a);
n = diff(find([true, d>min(d), true]));
out = mat2cell(a,1,n);
end
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 12 月 14 日
Another method -
a1=[1 2 3 4 5 10 11 12 13 18 19 20 21 22 23];
a2 = split_vector(a1)
a2 = 1×3 cell array
{[1 2 3 4 5]} {[10 11 12 13]} {[18 19 20 21 22 23]}
a1=[1 2 3 4 5 6 7 8 9 10 11 12 13 18 19 20 21 22 23];
a2 = split_vector(a1)
a2 = 1×2 cell array
{[1 2 3 4 5 6 7 8 9 10 11 12 13]} {[18 19 20 21 22 23]}
a1=[1 2 3 4 11 12 13 18 19 20 21 22 23 30 31 32 33 40 41 42];
a2 = split_vector(a1)
a2 = 1×5 cell array
{[1 2 3 4]} {[11 12 13]} {[18 19 20 21 22 23]} {[30 31 32 33]} {[40 41 42]}
function out = split_vector(a)
idx = [find(diff(a)~=1) numel(a)];
out = mat2cell(a, 1, [idx(1) diff(idx)]);
end

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

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by