【问题标题】:How to take the mean of columns from an array within an array?如何从数组中的数组中获取列的平均值?
【发布时间】:2013-02-28 13:36:18
【问题描述】:

我目前正在 Matlab 中从事一个项目,其中我有一个单元数组。第一个元胞数组长 464 列,深 1 行。这些单元中的每一个都是另一个 96 列和 365 行的单元阵列。我需要能够获得 464 个数组中每个数组的 96 列的平均值,并将 464 个数组中的每个数组放在一个称为均值的新数组中的不同行上。我试图编写代码来只做一列如下:

    mean = Homes{1,1}(1:)

但是当我尝试运行这段代码时,我得到了以下错误:

    mean = Homes{1,1}(1:)
                       |
    Error: Unbalanced or unexpected parenthesis or bracket.

基本上,我的最终数组名称意味着需要 96 列乘 464 行。我被困住了,真的可以使用你的帮助。

谢谢。

【问题讨论】:

  • (1:)肯定不行,你可以试试(1,:)。我永远不知道如何处理单元阵列。我认为如果你在顶部单元格数组中放置一个循环并将每个单元格分配给一个临时变量,你肯定可以得到一个平均值。
  • 尝试使用 cellfun。您可以试试 cellfun(@mean,Homes),这会将 mean 函数应用于元胞数组中的每个元素。
  • 当我尝试 cellfun(@mean,Homes) 时,我收到了这条消息...均值误差(第 28 行)y = sum(x)/size(x,dim);
  • 现在当我尝试。 Mean = mean(Homes{1,1}(:,1)) 我收到以下错误。我不确定为什么。 'cell' 类型的输入参数的未定义函数 'sum'。均值误差(第 28 行)y = sum(x)/size(x,dim);然而,当我输入 Homes{1,1}(:,1) 时,第一列会返回给我。

标签: matlab multidimensional-array mean cell-array


【解决方案1】:

我建议您在较小的矩阵上尝试以下代码。看看它是否能给你想要的结果。

a=cell(1,4); %for you it will be a=cell(1,464)
for i=1:4
   a{i}=randi(10,[5 10]); %for you it will be a{i}=randi(10,[365 96]);
end
a1=cell2mat(a);  %just concatenating
a1=mean(a1); %getting the mean for each column. in your case, you should get the mean for 96*464
a2=reshape(a1,[10 4]); %now what reshape does it it takes first 10 elements and arranges it into first column.
%Therefore, since I finally want a 4x10 matrix (in your case 464x96), i.e. mean of 10 elements in first cell array on first row and so on...
%Thus, 1st 10 elements should go to first column after doing reshape (since you want to keep them together). Therefore, instead of directly making matrix as 4x10, first make it as 10x4 and then take transpose (which is the next step).

a2=a2'; %thus you get a 4x10 matrix.

具体而言,代码将是

a=cell(1,464); 
for i=1:464
   a{i}=randi(10,[365 96]); 
end
a1=cell2mat(a);  
a1=mean(a1); 
a2=reshape(a1,[96 365]);                        
a2=a2'; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2021-08-30
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多