Azzera filtri
Azzera filtri

generating 10 samples from a binomial using a fair dice.

1 visualizzazione (ultimi 30 giorni)
clc
clear all
format compact
rng(970,'v4')
U=[];
X=[];
R = rand(10,1) % generate a sample in Unif(0,1)
P = [1/6,2/6,3/6,4/6,5/6,1];
js = [1:6]; F = cumsum(P); disp(F)
if R < 1/6
x=1
X=[Xx]
U=[UR];
else if R >= 1/6 & R <2/6
x=2
X=[Xx]
U=[UR];
else if R >= 2/6 & R < 3/6
x=3
X=[Xx]
U=[UR];
else if R >= 3/6 & R < 4/6
x=4
X=[Xx]
U=[UR];
else if R >= 4/6 & R < 5/6
x = 5
X=[Xx]
U=[UR];
else if R >=5/6 & R < 1
x=6
X =[Xx]
U=[UR];
end
end
end
end
end
end
i wanted my outcome to come out in terms of 1,2,3,4,5,6 when my x are these values

Risposta accettata

James Tursa
James Tursa il 2 Mar 2015
Modificato: James Tursa il 2 Mar 2015
First, to fix your code I am guessing you are getting error messages about Xx and UR as functions or variables. To concatenate variables like you are attempting you need to put a space inbetween the variables. E.g., instead of [Xx] and [UR] use [X x] and [U R]. (But this is still not totally correct ... see second point below).
Second, you don't have a loop defined to run over the values of R ... you use R in your "if" statements like it was a scalar when in fact it is a 10 element vector. You need a loop around all of your "if-else" code and index into R inside that loop. E.g.,
R = rand(10,1) % generate a sample in Unif(0,1)
P = [1/6,2/6,3/6,4/6,5/6,1];
js = [1:6]; F = cumsum(P); disp(F)
for k=1:numel(R) % Loop over all elements of R
if R(k) < 1/6
x = 1;
X = [X x];
U = [U R(k)]; % Why are you saving R in U since you already have R?
else if R(k) >= 1/6 && R(k) <2/6 % Note use of logical operator &&
x = 2;
X = [X x];
U = [U R(k)];
(etc)
end % End of for loop
Third, there are better ways to do this that don't involve all of these if-then-else tests explicitly. Suppose instead of 6 values you needed some code that dealt with 100's of values. You would be faced with copying the if-then-else blocks 100's of times in your code to deal with all of the levels. Just as a start, you might consider what you get with the following expression:
R(k) > P
How could you use this result to come up with the x value directly without any if-then-else tests?

Più risposte (0)

Categorie

Scopri di più su MATLAB Support Package for Raspberry Pi Hardware in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by