2015-11-09 80 views
-1

我有一個變量age,其中包含100名患者(年齡20至80歲)的年齡。matlab隨機抽樣變量x次獲得y的均值

我想編寫代碼來隨機選擇從該樣本100例(一個病人可出現一次以上)10例患者得到的45

,平均年齡有誰知道我能做到這一點?

+1

['randsample'](http://www.mathworks.com/help/stats/randsample.html)如果您有統計工具箱。或者只是生成[隨機整數](http://www.mathworks.com/help/matlab/math/random-integers.html)來索引。 – excaza

+1

我們不是在這裏寫你的代碼。請先嚐試一下,如果遇到困難,可以問一個包含[mcve]的問題,詳細說明您遇到的問題。 – Adriaan

回答

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