Histogram only returns one output.

4 views (last 30 days)
I am trying to plot a histogram that shows the first digit of any generated number, but when I run the code, it only plots for the last output. For example, if I run the code and the last value for out is 5, the histogram will only plot the 5. Any suggestions?
rng('shuffle')
A = randperm(100,10)
for X = A;
Y = num2str(X)
out = str2num(Y(1))
for out = str2num(Y(1))
histogram(X,9)
end
end

Accepted Answer

Image Analyst
Image Analyst on 4 Dec 2022
Try this:
rng('shuffle')
A = randperm(100, 10)
A = 1×10
83 10 44 41 4 62 96 45 33 39
theHistogram = zeros(1, 10);
for k = 1 : numel(A)
strNumber = sprintf('%d', A(k));
thisFirstNumber(k) = str2double(strNumber(1));
theHistogram(thisFirstNumber(k) + 1) = theHistogram(thisFirstNumber(k) + 1) + 1;
end
% Show first digits in command window:
thisFirstNumber
thisFirstNumber = 1×10
8 1 4 4 4 6 9 4 3 3
% Plot the histogram.
bar(0:9, theHistogram);
xlabel('First Digit of Number')
ylabel('count')
grid on;

More Answers (0)

Community Treasure Hunt

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

Start Hunting!