简体   繁体   中英

Histogram of multiple dataset with different dimension in Matlab

I can plot multiple plots with a same dimension in a histogram

x = rand(1000,3);
hist(x);

在此处输入图像描述

But I could not plot multiple plots with a different dimension.

x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);
x = [x1 x2 x3]
hist(x)

I get the following error

Error using horzcat
Dimensions of arrays being concatenated are not consistent.

Please someone point me to right direction to solve the problem.

Triple Bar Histogram (3 datasets)

You can use the histogram() function and retrieve the .binCounts of each histogram and concatenate them in a fashion that gives a 10 by 3 array. By calling bar() on this 10 by 3 array you'll get a similar binning graph that shows the histogram of 3 datasets with the bins shown as triple bars. Also a good idea to use the histogram() function as the use of hist() is no longer recommended by MATLAB.

三条柱状图

x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);

h1 = histogram(x1);
Counts_1 = h1.BinCounts;
h2 = histogram(x2);
Counts_2 = h2.BinCounts;
h3 = histogram(x3);
Counts_3 = h3.BinCounts;

Bin_Edges = h3.BinEdges;
Bin_Width = h3.BinWidth;
Bin_Centres = Bin_Edges(1:end-1) + Bin_Width/2;

Counts = [Counts_1.' Counts_2.' Counts_3.'];
bar(Counts);
title("Triple Bar Histogram");
xlabel("Bin Centres"); ylabel("Count");
set(gca,'xticklabel',Bin_Centres);

Ran using MATLAB R2019b

Well the problem is indeed that you cant add non size matching vars.

Here is a patch work for you: the magic is the Nan variable that make your code match

% its bad habits but:
x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);

% make em' all the same size
max_size = max([length(x1),length(x2),length(x3)]);

% add in the ending nan 
x1 = [x1; nan(max_size-length(x1), 1)];
x2 = [x2; nan(max_size-length(x2), 1)];
x3 = [x3; nan(max_size-length(x3), 1)];

% plot em' bad
x = [x1 x2 x3];
figure;
hist(x)

Its working great now: (but you know its a bit of a Frankenstein masterpiece :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM