【问题标题】:MATLAB - Working with accumarray with multiple categories?MATLAB - 使用具有多个类别的 accumarray?
【发布时间】:2017-02-20 04:07:55
【问题描述】:

我正在追问我的问题here,其中有一个完美的解决方案完全符合我的要求。但是我想知道如何应用这种方法,或者做类似的事情,如果不是是/否作为可能的响应,我会有两个以上的响应,例如是/否/也许。或者它将如何推广到 3 个以上的响应。

这是答案,重新格式化为我的问题:

假设我的数据如下所示:

responses = categorical(randi(3,1250,1),[1 2 3],{'no','yes','maybe'});
race = categorical(randi(5,1250,1),1:5,{'Asian','Black','BHispanic','White','WHispanic'});

我想对我的是/否数据做同样的事情,但有 3 种或更多的可能性。这将不再有效:

% convert everything to numeric:
yn = double(responses); 
rac = double(race);
% caluculate all frequencies:
data = accumarray(rac,yn-1);
data(:,2) = accumarray(rac,1)-data;
% get the categories names:
races = categories(race);   
answers = categories(responses);
% plotting:
bar(data,0.4,'stacked');
ax = gca;
ax.XTickLabel = races; % set the x-axis ticks to the race names
legend(answers) % add a legend for the colors
colormap(lines(3)) % use nicer colors (close to your example)
ylabel('YES/NO/MAYBE')% set the y-axis label
% some other minor fixes:
box off
ax.YGrid = 'on';

我不确定是否有办法使用 accumarray 方法来执行此操作,因为根据我的理解,将其与 3 个可能的响应一起使用是没有意义的。我也想将其概括为 n 个可能的响应。

更新:我目前正在研究交叉表功能,直到现在我才发现!我想这可能是我正在寻找的功能。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    这是一个通用版本:

    % the data (with even more categories):
    yesno = categorical(randi(4,1250,1),1:4,{'no','yes','maybe','don''t know'});
    race = categorical(randi(5,1250,1),1:5,{'Asian','Black','BHispanic','White','WHispanic'});
    % convert everything to numeric:
    yn = double(yesno); 
    rac = double(race);
    % caluculate all frequencies:
    data = accumarray([rac yn],1);
    % get the categories names:
    races = categories(race);   
    answers = categories(yesno);
    % plotting:
    bar(data,0.4,'stacked');
    ax = gca;
    ax.XTickLabel = races; % set the x-axis ticks to the race names
    legend(answers) % add a legend for the colors
    colormap(lines(numel(answers))) % use pretier colors
    ylabel('YES/NO')% set the y-axis lable
    % some other minor fixes:
    box off
    ax.YGrid = 'on';
    

    结果:

    在一张桌子上:

    T = array2table(data.','VariableNames',races,'RowNames',answers)
    

    输出:

    T = 
                      Asian    Black    BHispanic    White    WHispanic
                      _____    _____    _________    _____    _________
        no            58       72       69           66       62       
        yes           58       53       72           54       58       
        maybe         63       62       67           62       61   
        don't know    58       57       66           58       74      
    

    正如您已经提到的,您可以将crosstab 用于相同的任务。 crosstab(rac,yn) 会给你与accumarray([rac yn],1) 相同的结果。我认为accumarray 更快,虽然我没有检查它。

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 1970-01-01
      • 2015-07-25
      • 2015-04-12
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多