Mean of a cell array with different cell sizes?

1 回表示 (過去 30 日間)
Sim
Sim 2023 年 11 月 28 日
コメント済み: Sim 2023 年 11 月 28 日
Mean of a cell array with different cell sizes?
% This works:
a = {[1 3 4 5];[7 7 8 2];[5 4 1 9]}
a = 3×1 cell array
{[1 3 4 5]} {[7 7 8 2]} {[5 4 1 9]}
mean(cell2mat(a),2)
ans = 3×1
3.2500 6.0000 4.7500
% but this does not work:
a = {[1 3 4 5];[7 7 8 2];[5 4 1]}
a = 3×1 cell array
{[1 3 4 5]} {[7 7 8 2]} {[ 5 4 1]}
mean(cell2mat(a),2)
Error using cat
Dimensions of arrays being concatenated are not consistent.

Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 11 月 28 日
If the data in the cell array is compatible for concatenation, concatenate them and use mean for the specific dimension -
a = {[1 3 4 5];[7 7 8 2];[5 4 1 9]}
a = 3×1 cell array
{[1 3 4 5]} {[7 7 8 2]} {[5 4 1 9]}
b = cat(1,a{:})
b = 3×4
1 3 4 5 7 7 8 2 5 4 1 9
m = mean(b, 2)
m = 3×1
3.2500 6.0000 4.7500
If the data in the cell array is not compatible for concatenation, the best approach would be to pre-allocate the output and use a for loop. You could use cellfun() but that is just a for loop in disguise.
  6 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 11 月 28 日
@Sim, Using the name-argument pair will give the output as a cell array.
a = {[1 3 4 5];[7 7 8 2];[5 4 1]}
a = 3×1 cell array
{[1 3 4 5]} {[7 7 8 2]} {[ 5 4 1]}
cellfun(@mean,a)
ans = 3×1
3.2500 6.0000 3.3333
Sim
Sim 2023 年 11 月 28 日
ah ok, even better! Super thank you!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by