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

2 ビュー (過去 30 日間)
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!

採用された回答

Star Strider
Star Strider 2023 年 2 月 1 日
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.
.
  2 件のコメント
Kendell
Kendell 2023 年 2 月 1 日
@Star Strider Thank you for the assistance. Sorry for the lack of information. This is closer to what I am trying to get for the solution, so this is very helpful!
Star Strider
Star Strider 2023 年 2 月 1 日
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by