我有一个c
大小相等的数组,即size(c{n}) = [ m l ... ]
任何n
. 如何在一次扫描中获取所有数组元素的mean
值(在单元格数组索引上求平均值)?n
我考虑过使用cell2mat
andmean
但前者没有添加另一个维度,而是更改l
为l*n
. 当然,手动循环需要永远......
6 回答
如果所有数组的大小都相同,则将它们存储在矩阵而不是元胞数组中更有意义。这使得跨它们执行操作变得更容易,比如取平均值。您可以使用函数NDIMS和CAT将数据转换为矩阵:
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 = mean(M,dim+1); %# Get the mean across arrays
如果你有更高版本的matlab,可以通过'cellfun'函数来完成。这可以处理具有不等大小数组的单元格。
C = {1:10, [2; 4; 6], []};
Cmeans = cellfun(@mean, C)
Cmeans =
5.5000 4.0000 NaN
Reference: https://groups.google.com/forum/?fromgroups=#!topic/comp.soft-sys.matlab/S_hyHxy11f0
你在正确的轨道上。使用CELL2MAT将您的元胞数组转换为数值数组,然后使用 RESHAPE构造一个三维矩阵。然后,您可以使用带有维度参数的MEAN函数计算平均值:
>> c = {[1 2 3; 4 5 6] [7 8 9; 12 13 14]} c = [2x3 双] [2x3 双] >> 平均(重塑(cell2mat(c), [2, 3, 2]), 3) 答案= 4 5 6 8 9 10
I found an easy way to find the mean values within a Cell array on the following link: http://www.gomatlab.de/cellfun-t25114.html
May x
be the cell. Then:
var_mean = cellfun(@mean, x, 'UniformOutput', false); %columnwise mean value
var_mean = cellfun(@(in) mean(in(:)), x); %% mean value of the total "subcell"
这只是循环通过单元格并意味着数组向下直到它是一个单例。不需要那么长时间,这意味着 4000 万个浮点数,需要 1 秒。
function n = big_mean
tic
c = cell(1000);
for ii = 1:length(c)
c{ii} = rand(8,7,6,5,4,3,2);
end
n = all_cells(c);
toc
end
function n = all_cells(c)
n = zeros(length(c),1);
for ii = 1:length(c)
n(ii) = cell_mean(c{ii});
end
n = mean(n);
end
function n = cell_mean(n)
while length(size(n))~=2
n = mean(n);
end
end
Elapsed time is 1.042459 seconds.
ans =
0.4999
thanks for your other comments, but sometimes, it is hard to rearrange the data or change the way they are saved. For those of you who have this issue, here is the solution, Enjoy.
a=0;
MyCellAddFun=@(Input) a*eye(size(Input))+Input;
temp=arrayfun(@(ind) MyCellAddFun(CellData{ind}),1:length(CellData),'uniformoutput',false);
answer=temp{end}