How do I make a bar graph from uneven arrays without adding zeros to the end of the smaller array?

1 view (last 30 days)
a1 = randi([0,800],1,2251);
a2 = randi([0,800],1,2347);
figure()
X1 = categorical({'red','green'});
X1 = reordercats(X1,{'red','green'});
Y1 = [a1;a2];
bar(X1,Y1);
xlabel({'Apples'},'FontWeight','bold');
ylabel({'Number of Apples'},'FontWeight','bold');
The problem comes in @ Y1. It wants to combine the two arrays, assuming because they are of different sizes. I am trying to create one row with 2 columns that are of different sizes. I don't think it is possible like that on MATLAB, but i do not want to have to add zeros to the end of the larger array just to be able to combine them. Is there an alternate way, possibly a loop, that would add zeros to the end of the smaller array everytime? That would be my next stab at trying to solve the problem. Any help is greatly appreciated!

Accepted Answer

Star Strider
Star Strider on 1 Feb 2023
I am not certain what you want.
This approach creates a NaN matrix with the column length of the larger vector, writes the original vectors to it, and then plots them. (I shortened the original vectors because the longer ones took too long (more than 55 seconds) to render here.)
% a1 = randi([0,800],1,2251);
% a2 = randi([0,800],1,2347);
a1 = randi([0,800],1,51);
a2 = randi([0,800],1,47);
maxlen = max(cellfun(@(x)size(x,2), {a1,a2}));
Y1 = NaN(2,maxlen);
Y1(1,1:numel(a1)) = a1;
Y1(2,1:numel(a2)) = a2;
Y1
Y1 = 2×51
696 461 727 17 556 534 77 677 734 344 363 752 523 41 760 52 619 753 701 763 322 545 46 297 296 650 270 763 795 477 353 546 617 610 129 89 652 763 578 263 321 2 617 774 613 556 220 169 590 716 131 36 336 485 96 585 54 153 770 339
figure()
X1 = categorical({'red','green'});
X1 = reordercats(X1,{'red','green'});
bar(X1,Y1);
xlabel({'Apples'},'FontWeight','bold');
ylabel({'Number of Apples'},'FontWeight','bold');
I doubt that a loop is necessary.
.

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!