Breaking and spliting vector into groups and averaging

3 ビュー (過去 30 日間)
Albert
Albert 2021 年 3 月 10 日
編集済み: Albert 2021 年 3 月 11 日
Hi,
I have a long one-dimensional time vector that I want to split in chunks and average each chunk. I have another logical vector (same length) of 0s and 1s that changes the sign to signal each chunk transition. How could I easily use the information on the logical vector to select each chunk of the time vector?
Thanks!
timevec = [0 2 3 4 5 0 9 3 4];
chunk = [0 0 0 1 1 1 1 0 0];

採用された回答

Adam Danz
Adam Danz 2021 年 3 月 10 日
編集済み: Adam Danz 2021 年 3 月 10 日
timevec = [0 2 3 4 5 0 9 3 4];
chunk = [0 0 0 1 1 1 1 0 0];
g = cumsum([1, diff(chunk)]~=0); % assuming 'chunk' is a row vector
groupMeans = splitapply(@mean, timevec, g)
groupMeans = 1×3
1.6667 4.5000 3.5000
  5 件のコメント
Adam Danz
Adam Danz 2021 年 3 月 11 日
To define groups by the chunk vector resetting to 0,
chunk = [0 0 0 1 1 1 1 0 0 0 0 1]
chunk = 1×12
0 0 0 1 1 1 1 0 0 0 0 1
g = cumsum(diff([1,chunk])==-1)
g = 1×12
1 1 1 1 1 1 1 2 2 2 2 2
For the second question, do you mean this?
timevec = [0 2 3 4 5 0 9 3 4];
chunk = [0 0 0 1 1 1 1 0 0];
cond = logical([1 1 1 1 0 0 1 1 1]);
X = timevec(cond);
Y = chunk(cond);
g = cumsum([1, diff(Y)]~=0);
groupMeans = splitapply(@mean, X, g)
Albert
Albert 2021 年 3 月 11 日
編集済み: Albert 2021 年 3 月 11 日
For the first question, great, I didn't think it was so easy the adaptation!
For the second question it's a bit trickier because the Y array, after applying the condition in cond may totally mess around the chunks computation in the lines later on (transitions may be lost after applying the condition!). As a workaround I computed the chunks for all the values and applied the condition afterwards when computing the mean through a custom function as:
timevec = [0 2 3 4 5 0 9 3 4];
chunk = [0 0 0 1 1 1 1 0 0];
cond = logical([1 1 1 1 0 0 1 1 1]);
g = cumsum([1, diff(chunk)]~=0);
groupMeans = splitapply(@(vec,con)mean(vec(con)), timevec, cond, g)

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by