How to write a function for a certain number of random numbers

조회 수: 1 (최근 30일)
Cole Bromfield
Cole Bromfield 2020년 1월 16일
댓글: David Hill 2020년 1월 16일
My assignment says:
"Create an .m file that is a function that creates an array of N random integers in the range from -9999 to 9999. It should be in the form of x=randint(N)."
But I have no idea how to do that. I've tried everything. This is due in 4 days.

답변 (2개)

David Hill
David Hill 2020년 1월 16일
function out=randint(N)
out=randi(19999,1,N)-10000;
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 1월 16일
randi accepts a lower and upper bound directly
David Hill
David Hill 2020년 1월 16일
Thanks for the comment. Good reason to look at the documentation.
out=randi([-9999,9999],1,N);

댓글을 달려면 로그인하십시오.


Meg Noah
Meg Noah 2020년 1월 16일
If the numbers are supposed to be uniformly distributed, then they are between 0 and 1. So just linearly scale the value 0 to the minimum and value 1 to the maximum. Subtract 0.5 to make it zero mean. Multiply by the range (max-min). If the result supposed to have a 0 mean (which your example does), then the offset needs to adjusted. The min after doing that will be -range*0.5. Add range*0.5 and subtract the minvalue. For example, a histogram of 1000 points between -5 and 5 is:
histogram(2*5*rand(1000)-5)
If you want a normal distribution, and you don't have the statistics toolbox, you have to write your own. This will do:
function [harvest] = getRandomGaussianDistribution(nvals)
N = ceil(nvals/2);
v1 = rand(N,1);
v2 = rand(N,1);
idx = 1:N;
while (~isempty(idx))
v1(idx) = rand(numel(idx),1);
v2(idx) = rand(numel(idx),1);
v1(idx) = 2*v1(idx) - 1;
v2(idx) = 2*v2(idx) - 1;
rsq = v1.^2 + v2.^2;
idx = find(rsq >= 1.0 | rsq <= 0);
end
rsq = sqrt(-2.0.*log(rsq)./rsq);
harvest = vertcat(v1.*rsq, v2.*rsq);
harvest = (harvest-mean(harvest)./std(harvest));
harvest = harvest(1:nvals);
end
Then you have to search and exclude outliars because of the nature of statistics. Normalization is done by subtracting the mean and dividing by the standard deviation.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by