You can do what you want using unique and histc to get unique values ββand frequency, and then use the 'stacked' option in bar to print the data. Note that later on I took level and age as column vectors. I also made the central parts of the code, not for this specific example.
level=[8,8,8,9,9,9,9]'; %'#SO code formatting age=[10,11,11,10,11,11,11]'; %' %#get unique values and frequency count uniqLevel=unique(level); freqLevel=histc(level,uniqLevel); uniqAge=unique(age); %#combine data in a manner suitable for bar(...,'stacked') barMatrix=cell2mat(arrayfun(@(x)histc(age(level==uniqLevel(x)),uniqAge),... 1:numel(uniqLevel),'UniformOutput',false)); %#plot the stacked bars and customize hb=bar(barMatrix','stacked'); %' set(gca,'xticklabel',uniqLevel,'ytick',1:max(sum(barMatrix))) set(hb(uniqAge==10),'facecolor','green') set(hb(uniqAge==11),'facecolor','red') xlabel('Level') ylabel('Occurrence') legend('10','11','location','northwest')

source share