I have to make a histogram about the times a variable is <=13, so I made this code but after about half an hour it crashed the site and said
Error code: Out of memory
Hw can I make it use less memory and execute quicker?
A=zeros(1,10000) %array to store the X values
for(j=0:1:10000) %rand 1000 times, if rand <=13, x++, 10000 times
x=0
for(i=0:1:1000)
data=randi([0,100])
if(data<=13)
x=x+1
end
end
A(1,j+1)=x
end
histogram(A) %histogram of value of x, and the times it had that value

 Réponse acceptée

Image Analyst
Image Analyst le 29 Mai 2022

1 vote

Try it this way:
tic;
numExperiments = 10000;
numRandPerExperiment = 1000;
A = zeros(1,numExperiments); %array to store the X values
for j = 0 : numExperiments-1 %rand 1000 times, if rand <=13, x++, 10000 times
% Get 1000 random numbers.
data = randi([0,100], numRandPerExperiment, 1);
% Count how many are 13 or less.
numBelow13forThisRun = sum(data <= 13);
% Store that number.
A(j+1)= numBelow13forThisRun;
end
histogram(A) %histogram of value of x, and the times it had that value
grid on;
xlbl = sprintf('Number of times 13 or less in %d numbers', numRandPerExperiment)
xlabel(xlbl);
ylabel('Count')
caption = sprintf('Results of %d experiments of %d random numbers per experiment', numExperiments, numRandPerExperiment)
title(caption)
toc;
Elapsed time is 0.297138 seconds.

Plus de réponses (0)

Produits

Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by