简体   繁体   English

3D数组的第3维的总和

[英]Aggregate 3rd dimension of a 3d array for the subscripts of the first dimension

I have a 3 Dimensional array Val 4xmx2 dimension. 我有一个3维数组Val 4xmx2维。 (m can be variable) (米可以是可变的)

Val{1} = [1, 280; 2, 281; 3, 282; 4, 283; 5, 285];
Val{2} = [2, 179; 3, 180; 4, 181; 5, 182];
Val{3} = [2, 315; 4, 322; 5, 325];
Val{4} = [1, 95; 3, 97; 4, 99; 5, 101];

I have a subscript vector: 我有一个下标向量:

subs = {1,3,4};

What i want to get as output is the average of column 2 in the above 2D Arrays (only 1,3 an 4) such that the 1st columns value is >=2 and <=4. 我想要获得的输出是上述2D数组中第2列的平均值(仅1,3和4),这样第1列的值是> = 2和<= 4。

The output will be: {282, 318.5, 98} 输出将是:{282,318.5,98}

This can probably be done by using a few loops, but just wondering if there is a more efficient way? 这可以通过使用一些循环来完成,但是只是想知道是否有更有效的方法?

Here's a one-liner: 这里是单线:

output = cellfun(@(x)mean(x(:,1)>=2 & x(:,1)<=4,2),Val(cat(1,subs{:})),'UniformOutput',false);

If subs is a numerical array (not a cell array) instead, ie subs=[1,3,4] , and if output doesn't have to be a cell array, but can be a numerical array instead, ie output = [282,318.5,98] , then the above simplifies to 如果subs是一个数值数组(而不是一个单元格数组),即subs=[1,3,4] ,并且output不必是一个单元格数组,而可以是一个数值数组,即output = [282,318.5,98] ,则上述内容简化为

output = cellfun(@(x)mean(x(x(:,1)>=2 & x(:,1)<=4,2)),Val(subs));

cellfun applies a function to each element of a cell array, and the indexing makes sure only the good rows are being averaged. cellfun将一个函数应用于单元格数组的每个元素,并且索引可确保仅对好行进行平均。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM