【问题标题】:Using matlab to arrange and sort data使用matlab对数据进行排列和排序
【发布时间】:2017-03-14 07:27:37
【问题描述】:

我的数据是一个包含两列格式的 excel 文件:

Date           Type
3/12/06        A
3/12/06        B
3/12/06        B
3/12/06        C
6/01/07        A
6/01/07        A
8/01/07        B
...

A 列是日期,可以重复,而 B 列是这些日期的观察类型。

在 MATLAB 中,我想将每种类型绘制为时间的函数,但首先我需要整理我的数据。通常有多个相同的行对应于同一日期同一类型的多个观测值。所以我想首先我需要计算某种类型在同一天发生了多少次?

任何帮助都会很棒!我仍处于尝试以正确格式读取日期的阶段......

【问题讨论】:

  • 为什么要统计重复数据?你想如何在情节中显示它?
  • @Adiel 我想要每个类型的观察次数随时间变化的折线图
  • 我认为每种类型的堆积条形图也会起作用
  • 您是如何尝试将这些数据读入 Matlab 的?向我们展示您尝试过的任何代码...

标签: matlab


【解决方案1】:

这是一个解决方案:我用特定索引替换每种类型和每个日期,然后使用 accumarray 来创建 2D 数据透视表。您也可以直接使用excel中的功能数据透视表。

% We load the xls file.
[~,txt] = xlsread('test.xls');
% We delete the header:
txt(1,:) = [];
% Value and index for the date:
[val_d,~,ind_d] = unique(txt(:,1));
% Value and index for the type:
[val_c,~,ind_c] = unique(txt(:,2));
% We use accumarray to create a pivot table that count each occurence.
acc = accumarray([ind_d,ind_c],1)

% Then we simply plot the result:
dateFormat = 'dd/mm/yy';   
for i = 1:length(val_c);
  subplot(1,length(val_c),i)
  bar(datenum(val_d,dateFormat),acc(:,i),1) % easier to deal with datenum
  datetick('x',dateFormat)
  xlabel('Date')
  ylabel([val_c{i},' count'])
  ylim([0,3])
end

结果:

【讨论】:

  • 感谢@obchardon 这个例子!我收到此错误Error using datenum (line 181) DATENUM failed. Caused by: Error using dtstr2dtnummx Failed to convert from text to date number. 我正在使用 Matlab 2016b
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 2012-03-25
相关资源
最近更新 更多