2017-02-20 12 views
1

我要求跟進我的問題here,其中有一個完美的解決方案,完全符合我的要求。但是我想知道如何應用這種方法,或者做類似的事情,如果不是可能的答案,我會有2個以上的答覆,所以是/否/也許,例如。或者它如何推廣到3個以上的迴應。MATLAB - 使用多個類別的準數據?

這就是答案,重新格式化爲我的問題:

假設我的數據是這樣的:

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'}); 

我想經歷和做同樣的事情與我的是/否數據,但要做到這一點有三種可能性,或更多。這樣就不會結束工作了:

% 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個可能的反應。

更新:我目前正在調查迄今爲止根本找不到的交叉表功能!我認爲這可能是我正在尋找的功能。

回答

0

這裏是一個廣義的版本:

% 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'; 

結果:

​​3210

而在一個表:

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更快,但我沒有檢查它。

相關問題