How to make a properablity eqautions

7 次查看(过去 30 天)
Rainaire Hansford
回答: BhaTTa 2025-8-14,8:50
Hello MathWorks,
I want to make a program that calculates properablity or chances of selected numbers. However I also want to make a program that show the selected numbers. For explain you know how fliping a coin is 50/50 but when you flip its either head or tails. I would like to make a program where I can have a setting or range of numbers between for ex 1 to 10 and the program run 3 numbers between that range and tell me its probability. I know its simple i just dont know how to do it. Thank you

回答(1 个)

BhaTTa
BhaTTa 2025-8-14,8:50
Hey @Rainaire Hansford, I have attached simple MATLAB script that will:
  1. Let you specify a range of integers (e.g. 1 to 10).
  2. Randomly draw N numbers from that range (with or without replacement).
  3. Display each draw.
  4. Repeat the experiment M times to estimate the probability of each possible number appearing in the draw.
below i have attached the code, please take it as reference and modify it accordingly:
%% SETTINGS
minVal = 1; % Minimum in range
maxVal = 10; % Maximum in range
Ndraw = 3; % How many numbers drawn each trial
withRepl = false; % true = allow repeats, false = no repeats
Mtrials = 10000; % How many experiments to run
%% PREPARE
values = minVal:maxVal;
K = numel(values);
countHits = zeros(1,K); % count of times each value was drawn
allDraws = zeros(Mtrials,Ndraw); % record of every draw
%% RUN EXPERIMENTS
for t = 1:Mtrials
if withRepl
% Draw Ndraw samples with replacement
draw = values(randi(K,1,Ndraw));
else
% Draw Ndraw samples without replacement
draw = values(randperm(K,Ndraw));
end
allDraws(t,:) = draw;
% Count each drawn value
for v = draw
idx = v - minVal + 1; % index into countHits
countHits(idx) = countHits(idx) + 1;
end
end
%% DISPLAY ONE EXAMPLE
exampleRun = 1; % Change to any trial index 1..Mtrials
fprintf('Example draw #%d: ', exampleRun);
Example draw #1:
fprintf('%d ', allDraws(exampleRun,:));
10 9 8
fprintf('\n\n');
%% ESTIMATE PROBABILITIES
% Each trial draws Ndraw numbers, so total draws = Mtrials*Ndraw
totalDraws = Mtrials * Ndraw;
probEst = countHits / totalDraws;
% Show results in a table
T = table(values.', countHits.', probEst.', ...
'VariableNames',{'Value','Count','EstimatedProbability'});
disp(T);
Value Count EstimatedProbability _____ _____ ____________________ 1 3073 0.10243 2 2984 0.099467 3 2989 0.099633 4 2927 0.097567 5 3035 0.10117 6 3049 0.10163 7 2993 0.099767 8 3052 0.10173 9 2936 0.097867 10 2962 0.098733
%% PLOT THE DISTRIBUTION
figure;
bar(values, probEst);
xlabel('Value drawn');
ylabel('Estimated Probability');
title(sprintf('Estimated Probability of Drawing Each Value (%d trials × %d draws)', Mtrials, Ndraw));
grid on;

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by