Histogram only returns one output.
3 views (last 30 days)
Show older comments
Javid Miller
on 4 Dec 2022
Commented: Javid Miller
on 4 Dec 2022
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
0 Comments
Accepted Answer
Image Analyst
on 4 Dec 2022
Try this:
rng('shuffle')
A = randperm(100, 10)
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
% Plot the histogram.
bar(0:9, theHistogram);
xlabel('First Digit of Number')
ylabel('count')
grid on;
More Answers (0)
See Also
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!