MATLAB Cell Array-如果另一列匹配则取两个值的平均值 [英] MATLAB Cell Array - Average two values if another column matches

查看:309
本文介绍了MATLAB Cell Array-如果另一列匹配则取两个值的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元格数组,其中某些条目具有两个数据点.如果要在同一天收集数据,我想对两个数据点取平均值.

I have a cell array in which some of the entries have two data points. I want to average the two data points if the data were collected on the same day.

单元格数组"site"的第一列是日期.第四列是数据集中.如果数据来自同一天,我想对第四列取平均值.

The first column of cell array 'site' is the date. The fourth column is the data concentration. I want to average the fourth column if the data comes from the same day.

例如,如果我的细胞阵列看起来像这样:

For example, if my cell array looks like this:

01/01/2011  36-061-0069   1   10.4
01/01/2011  36-061-0069   2   10.1
01/04/2011  36-061-0069   1   7.9
01/05/2011  36-061-0069   1   13

我想将第四列(10.4和10.1)平均为一行,而其他所有内容保持不变.

I want to average the fourth column (10.4 and 10.1) into one row and leave everything else the same.

有帮助吗? if elseif循环会起作用吗?我不确定如何解决这个问题,尤其是因为单元阵列的工作原理与矩阵略有不同.

Help? Would an if elseif loop work? I'm not sure how to approach this issue, especially since cell arrays work a little differently than matrices.

推荐答案

您可以结合使用uniquediffaccumarray简洁地完成此操作.

You can do it succinctly without a loop, using a combination of unique, diff and accumarray.

定义数据:

data = {'01/01/2011'  '36-061-0069'  '1'  '10.4';
        '01/01/2011'  '36-061-0069'  '2'  '10.1';
        '01/04/2011'  '36-061-0069'  '1'  '7.9';
        '01/05/2011'  '36-061-0069'  '1'  '13'};

然后:

dates = datenum(data(:,1),2); % mm/dd/yyyy format. Change "2" for other formats
[dates_sort ind_sort] = sort(dates);
[~, ii, jj] = unique(dates_sort);
n = diff([0; ii]);
result = accumarray(jj,vertcat(str2double(data(ind_sort,4))))./n;

获得理想的结果:

result =

   10.2500
    7.9000
   13.0000

如果需要,您可以使用data(ind_sort(ii),1)获取未重复的排序日期.

If needed, you can get the non-repeated, sorted dates with data(ind_sort(ii),1).

代码说明:首先将日期转换为数字并进行排序.然后提取唯一日期和重复日期.最后,将重复行中的数据求和,然后除以重复次数即可得到平均值.

Explanation of the code: the dates are first converted to numbers and sorted. The unique dates and repeated dates are then extracted. Finally, data in repeated rows are summed and divided by the number of repetitions to obtain the averages.

Matlab 2013a以后的兼容性问题:

函数unique在Matlab 2013a中已已更改 .从该版本开始,将'legacy'标志添加到unique,即将[~, ii, jj] = unique(dates_sort)行替换为

The function unique has changed in Matlab 2013a. For that version onwards, add 'legacy' flag to unique, i.e. replace the line [~, ii, jj] = unique(dates_sort) by

[~, ii, jj] = unique(dates_sort,'legacy')

这篇关于MATLAB Cell Array-如果另一列匹配则取两个值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆