gabboshow
gabboshow

Reputation: 5569

calculate histogram of 2 variables

I have a vector containining the speed of 200 walks:

a = 50;
b = 100;
speed = (b-a).*rand(200,1) + a;

and another vector contaning the number of steps for each walk:

a = 8;
b = 100;
steps = (b-a).*rand(200,1) + a;

I would like to create a histogram plot with on the x axis the speeds and on the y axes the sum of the steps of each speed.

What I do is the following but I guess there is a more elegant way to do this:

unique_speed = unique(speed);
y_unique_speed  = zeros(size(unique_speed));
for i = 1 : numel(unique_speed)

    speed_idx = unique_speed(i);
    idx = speed==speed_idx ;
    y_unique_speed  (i) = sum(steps (idx));

end

Upvotes: 2

Views: 158

Answers (2)

nirvana-msu
nirvana-msu

Reputation: 4077

First you need to discretize your speed variable. Unlike in the other answer, the following allows you to choose arbitrary step size, e.g. I've chosen 1.5. Note that the last bin edge should be strictly more than the maximum data point, hence I used max(speed)+binstep. You can then use histc to determine which bin each pairs falls into, and accumarray to determine total number of steps in each bin. Finally, use bar to plot.

binstep = 1.5;
binranges = (min(speed):binstep:max(speed)+binstep)';
[~, ind] = histc(speed, binranges);
bincounts = accumarray(ind, steps, size(binranges));
hFig = figure(); axh = axes('Parent', hFig); hold(axh, 'all'); grid(axh, 'on');
bar(axh, binranges, bincounts); axis(axh, 'tight');

enter image description here

Upvotes: 1

Airidas Korolkovas
Airidas Korolkovas

Reputation: 328

First, bin the speed data to discrete values:

sspeed = ceil(speed);

and then accumulate the various step sizes to each bin:

numsteps = accumarray(sspeed, steps);
plot(numsteps)

Upvotes: 0

Related Questions