Calculate number appearance within a range

4 次查看(过去 30 天)
I need help calculating the number of times a number appears within a range. To be more specific, I need to specify how many times TT values are between [1, 2], then between (2, 10], then between (10, 20], then between (20, 50] then between and (50, 100].
classes=[1 2 10 20 50 100];
count=hist(TT,classes);

采纳的回答

Star Strider
Star Strider 2023-1-19
The histcounts and histogram functions are perfect for this —
LD = load(websave('TT','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1268555/TT.mat'));
TT = LD.TT
TT = 31×1
0 1.0000 14.9000 8.7000 1.0000 0 0 0 40.2000 10.3000
Edges = [1 2 10 20 50 100];
[BinCounts,Edges,Bin] = histcounts(TT, Edges);
BinCounts
BinCounts = 1×5
2 4 5 4 0
figure
histogram(TT, Edges)
xticks(Edges)
grid
xlim([min(Edges) max(Edges)])
xlabel('Bin Limits')
ylabel('Counts')
Thi histogram plot gives a better depiction of the bin limits than a bar plot of the histcounts results would.
.
  17 个评论
Askic V
Askic V 2023-1-25
@Star Strider can you please explain, how you upload file and use load command in th code, just like in the example
load(websave('TT','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1268555/TT.mat'));
Star Strider
Star Strider 2023-1-25
@Askic V — That is exactly how I do it, although I always load into a output variable so that I have some control over what loads, and so I can change the name of the variable used in the subsequent script if necessary. (Since I rarely use websave, credit for discovering this goes to @Karim, who was appropriately rewarded for discovering it.)

请先登录,再进行评论。

更多回答(1 个)

Askic V
Askic V 2023-1-19
Perhaps this code snippet will help you:
load TT
classes = [1 2 10 20 50 100];
tol = 1e-10;
res = zeros(size(diff(classes)));
for i = 1:numel(classes)-1
res(i) = sum(TT >= classes(i)-tol & TT < classes(i+1)+tol);
end
res

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by