我有一个变量age
,其中包含100名患者(年龄20到80岁)的年龄。
我想编写代码,从100名患者的样本中随机选择10名患者(一名患者可出现不止一次),以获得平均年龄45岁。
有谁知道我怎么能做到这一点?
答案 0 :(得分:0)
我原本想要了解Matlab中是否有可用于解决此问题的函数。然而,没有一个与兰特相关的命令似乎做了我需要做的事情(如果我错过了,我很抱歉)。
但是,我编写了以下代码来解决我的问题。在循环中,我允许从所需平均值的0.1变化(可以根据需要进行调整)。
% Make an array of 100 ages between 20 and 80
min=20;
max=80;
AgeArray = min + (max-min).*rand(100,1);
% Set parameters for randomselection
samplenr=10; % Want a 10 random samples from the original age array of 100
mean = 45; % The mean of randomly selected 10 sample should be 45
half_nr=samplenr/2; % Set the half-way point
% Get first random sample of 10 ages from the original array of 100
RandSubSample = datasample(AgeArray,samplenr);
% Sort the array of 10 from low to high values
RandSubSample=sort(RandSubSample);
% Mean of this random sample
sumage=sum(RandSubSample);
meanage=sumage/samplenr;
% Loop to re-select 10 samples until mean matches 45 (with error allowed for +/-
% 0.1
while meanage<mean-0.1 || meanage>mean+0.1
if meanage<mean % If mean is too low we need to replace young ages with older aged
index=randi([1 half_nr]);
RandSubSample(index)=r(randi(numel(r)));
elseif meanage>mean % If mean is too high we need to replace old age with younger age
index=randi([half_nr nr]);
RandSubSample(index)=r(randi(numel(r)));
end
RandSubSample=sort(RandSubSample);
sumage=sum(RandSubSample);
meanage=sumage/nr;
end
y=sort(y);
sumage=sum(y);
meanage=sumage/nr;
end