Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-14, 20:13   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何计算单元格阵列的加权平均值?

上一个问题的概括中,如何对单元元素(即本身并将保留为数组的元素)进行加权平均?

我将从修改gnovice的答案开始,如下所示:

dim = ndims(c{1}); %# Get the number of dimensions for your arrays M = cat(dim+1,c{:}); %# Convert to a (dim+1)-dimensional matrix meanArray = sum(M.*weigth,dim+1)./sum(weigth,dim+1); %# Get the weighted mean across arrays 在此之前,请确保weight具有正确的形状。我认为需要注意的三种情况是
  1. 权重= 1(或任何常数)=>返回通常的平均值
  2. numel(weight)== length(c)=>重量是每个单元元素c {n}(但对于固定n的每个数组元素均相等)
  3. numel(weight)== numel(cell2mat(c))=>每个数组元素都有自己的权重...
第一种情况很简单,第3种情况不太可能发生,所以目前我对第2种情况感兴趣:如何将权重转换为一个数组,以使M.*weight在上述总和中具有正确的维数?当然,也可以理解示出了另一种获得加权平均的方法的答案。

编辑实际上,如果权重与c具有相同的结构,则情况3比情况1更为琐碎(重言,道歉) 。

这是情况2的示例:

c = { [1 2 3; 1 2 3], [4 8 3; 4 2 6] }; weight = [ 2, 1 ]; 应该回来

meanArray = [ 2 4 3; 2 2 4 ] (例如,对于第一个元素(2 * 1 + 1 * 4)/(2 + 1)= 2)



回答:

在熟悉REPMAT之后 ,现在是我的解决方案:

function meanArray = cellMean(c, weight) % meanArray = cellMean(c, [weight=1]) % mean over the elements of a cell c, keeping matrix structures of cell % elements etc. Use weight if given. % based on http://stackoverflow.com/q/5197692/321973, courtesy of gnovice % (http://stackoverflow.com/users/52738/gnovice) % extended to weighted averaging by Tobias Kienzler % (see also http://stackoverflow.com/q/5231406/321973) dim = ndims(c{1}); %# Get the number of dimensions for your arrays if ~exist('weight', 'var') || isempty(weight); weight = 1; end; eins = ones(size(c{1})); % that is german for "one", creative, I know... if ~iscell(weight) % ignore length if all elements are equal, this is case 1 if isequal(weight./max(weight(:)), ones(size(weight))) weight = repmat(eins, [size(eins)>0 length(c)]); elseif isequal(numel(weight), length(c)) % case 2: per cell-array weigth weight = repmat(shiftdim(weight, -3), [size(eins) 1]); else error(['Weird weight dimensions: ' num2str(size(weight))]); end else % case 3, insert some dimension check here if you want weight = cat(dim+1,weight{:}); end; M = cat(dim+1,c{:}); %# Convert to a (dim+1)-dimensional matrix sumc = sum(M.*weight,dim+1); sumw = sum(weight,dim+1); meanArray = sumc./sumw; %# Get the weighted mean across arrays

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 22:53


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.