matlab移调&在嵌入式IF语句中排序

时间:2012-05-28 06:50:29

标签: matlab

我一直难以设法创建一个转换以下内容的if,else循环:

Subject: Date: Result:
AAA 02/01/12 10
AAA 02/02/12 12
AAA 02/03/12 14
BBB 02/01/12 25
BBB 02/02/12 26
BBB 02/03/12 27
CCC 01/01/12 66
CCC 01/02/12 70
CCC 01/03/12 75

我希望信息在列之间转换,如下所示:

SUBJECT 01/01/12 01/02/12 01/03/12 02/01/12 02/02/12 02/03/12
AAA RESULT
BBB RESULT
CCC RESULT

每列应该只有一个日期,每行只有一个主题。结果将匹配其各自的主题并放置在其适当的单元格中。数据可以包括几个主题,数千个主题,日期和结果。一些结果可能包含非数值(NaN)。此外,主题和日期可以是任何随机顺序,主题可以由数字和字符串字符组成。

UPDATE @amro& superbest

如果我有一个日期格式的文本文件:800317 == mar / 17/2080, 我如何导入并修改您编写的代码? 再次感谢。

2 个答案:

答案 0 :(得分:2)

如果您将数据存储在dataset array对象中,那么unstack方法就是您所寻找的方法(有时也称为从高到宽的转换)。


我编写了一个简单的示例,演示了如何在没有数据集类的情况下执行此操作:

%# cell array: subjects, dates, values
data = {
    'AA' '2012-05-01' 0.1
    'AA' '2012-05-03' 0.2
    'BB' '2012-05-02' 0.3
    'CC' '2012-05-01' 0.4
    'CC' '2012-05-02' 0.5
    'CC' '2012-05-03' 0.6
};

[subjects,~,subjectsMap] = unique(data(:,1));
[dates,~,datesMap] = unique(data(:,2));
M = nan(numel(subjects),numel(dates));
for i=1:numel(subjects)
    %# get all rows with subject == subject_i
    rIdx = (subjectsMap == i);
    %# fill values at this row for the specified columns
    M(i,datesMap(rIdx)) = cell2mat(data(rIdx,3));
end

D = cell(size(M)+1);
D(2:end,2:end) = num2cell(M);       %# fill values
D(1,2:end) = dates;                 %# column headers
D(2:end,1) = subjects;              %# row headers

这里是转换之前(高)和之后(广泛)的数据:

>> data
data = 
    'AA'    '2012-05-01'    [0.1]
    'AA'    '2012-05-03'    [0.2]
    'BB'    '2012-05-02'    [0.3]
    'CC'    '2012-05-01'    [0.4]
    'CC'    '2012-05-02'    [0.5]
    'CC'    '2012-05-03'    [0.6]

>> D
D = 
      []    '2012-05-01'    '2012-05-02'    '2012-05-03'
    'AA'    [       0.1]    [       NaN]    [       0.2]
    'BB'    [       NaN]    [       0.3]    [       NaN]
    'CC'    [       0.4]    [       0.5]    [       0.6]

答案 1 :(得分:1)

这是一个应该做你想做的事情的脚本:

% Clean up
clc
clear

% Hardcoded example input
input = {
    'AAA'    '02/01/12'    10
    'AAA'    '02/02/12'    12
    'AAA'    '02/03/12'    14
    'BBB'    '02/01/12'    25
    'BBB'    '02/02/12'    26
    'BBB'    '02/03/12'    27
    'CCC'    '01/01/12'    66
    'CCC'    '01/02/12'    70
    'CCC'    '01/03/12'    75
    };

% Figure out how many rows and columns there will be
header_row = unique(input(:, 2));
header_col = unique(input(:, 1));

% Pre-allocation for better performance
output = cell(length(header_col), length(header_row));

% Rearrange the array
for i = 1:size(input, 1)
    % Find to which date and subject this element belongs
    subject = find(strcmp(header_col, input{i, 1}));
    date = find(strcmp(header_row, input{i, 2}));

    % Put the value in the appropriate slot
    output{subject, date} = input{i, 3};
end

% Add header columns and rows and print the result
result = [['SUBJECT' header_row']; [header_col output]];