[go: up one dir, main page]

0% found this document useful (0 votes)
77 views26 pages

Matlab 1 Microsoft Word Document 1 PDF

The document discusses generating random numbers and simulating probabilistic systems in MATLAB. It covers generating discrete and continuous random variables, as well as examples of normal, binomial, multinomial and hypergeometric distributions. Code examples are provided to generate random numbers, compute probabilities and plot distribution functions.

Uploaded by

Hazel Hinai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views26 pages

Matlab 1 Microsoft Word Document 1 PDF

The document discusses generating random numbers and simulating probabilistic systems in MATLAB. It covers generating discrete and continuous random variables, as well as examples of normal, binomial, multinomial and hypergeometric distributions. Code examples are provided to generate random numbers, compute probabilities and plot distribution functions.

Uploaded by

Hazel Hinai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Work on the Matlab Commands in conjunction with the worked out examples given below.

A computer simulation is a computer program which attempts to represent the real world based
on a model. The accuracy of the simulation depends on the precision of the model. Suppose that
the probability of heads in a coin toss experiment is unknown. We can perform the experiment of
tossing the coin n times repetitively to approximate the probability of heads.
P(H) = (Number of times heads observed/ Number of times the experiment executed).

However, for many practical problems it is not possible to determine the probabilities by
executing experiments a large number of times. With today’s computers processing capabilities,
we only need a high-level language, such as MATLAB, which can generate random numbers, to
deal with these problems. In this chapter, we present basic methods of generating random
variables and simulate probabilistic systems. The provided algorithms are general and can be
implemented in any computer language. However, to have concrete examples, we provide the
actual codes in MATLAB. If you are unfamiliar with MATLAB, you should still be able to
understand the algorithms.
Generate Discrete Uniform Random Numbers
Pick a random sample of 10 from a list of 553 items.
rng default; % for reproducibility
numbers = unidrnd(553,1,10)
numbers =
451 501 71 506 350 54 155 303 530 534

Discrete and Continuous Random Number Generators: Most of the


programming languages can deliver samples from the uniform distribution to us (In reality, the given
values are pseudo-random instead of being completely random.) The rest of this section shows how
to convert uniform random variables to any other desired random variable. The MATLAB code for
generating uniform random variables is:
U = rand;
which returns a pseudorandom value drawn from the standard uniform distribution on the open
interval (0,1). Also
U = rand(m, n); returns an m-by-n matrix containing independent pseudorandom values drawn from
the standard uniform distribution on the open interval (0,1).
Normal,mean and variance
[m,v] = normstat(mu,sigma) returns the mean and variance of the normal distribution with mean mu and standard
deviation sigma.
The mean of the normal distribution with parameters µ and σ is µ, and the variance is σ2.
Compute the mean and variance of the normal distribution with parameters mu and sigma.
mu = 1;
sigma = 1:5;
[m,v] = normstat(mu,sigma)
m = 1×5

1 1 1 1 1

v = 1×5

1 4 9 16 25
Compute and Plot the Normal Distribution pdf
Compute the pdf of a standard normal distribution, with parameters μ equal to 0 and σ equal to 1.
x = [-3:.1:3];
norm = normpdf(x,0,1);
Plot the pdf.
figure;

plot(x,norm)
Multinomial Probability Distribution Objects
This example shows how to generate random numbers, compute and plot the pdf, and compute
descriptive statistics of a multinomial distribution using probability distribution objects.

Step 1. Define the distribution parameters.


Create a vector p containing the probability of each outcome. Outcome 1 has a probability of 1/2,
outcome 2 has a probability of 1/3, and outcome 3 has a probability of 1/6. The number of trials n in
each experiment is 5, and the number of repetitions reps of the experiment is 8.
p = [1/2 1/3 1/6];
n = 5;
reps = 8;
Step 2. Create a multinomial probability distribution object.
Create a multinomial probability distribution object using the specified value p for the
Probabilities parameter.
pd = makedist('Multinomial','Probabilities',p)
pd =
MultinomialDistribution

Probabilities:
0.5000 0.3333 0.1667

Step 3. Generate one random number.


Generate one random number from the multinomial distribution, which is the outcome of a single
trial.
rng('default') % For reproducibility
r = random(pd)
r = 2

This trial resulted in outcome 2.


Step 4. Generate a matrix of random numbers.
You can also generate a matrix of random numbers from the multinomial distribution, which reports
the results of multiple experiments that each contain multiple trials. Generate a matrix that contains
the outcomes of an experiment with n = 5 trials and reps = 8 repetitions.
r = random(pd,reps,n)
r =
3 3 3 2 1
1 1 2 2 1
3 3 3 1 2
2 3 2 2 2
1 1 1 1 1
1 2 3 2 3
2 1 3 1 1
3 1 2 1 1

Each element in the resulting matrix is the outcome of one trial. The columns correspond to the five
trials in each experiment, and the rows correspond to the eight experiments. For example, in the first
experiment (corresponding to the first row), one of the five trials resulted in outcome 1, one of the
five trials resulted in outcome 2, and three of the five trials resulted in outcome 3.

Step 5. Compute and plot the pdf.


Compute the pdf of the distribution.
x = 1:3;
y = pdf(pd,x);
bar(x,y)
xlabel('Outcome')
ylabel('Probability Mass')
title('Trinomial Distribution')

The plot shows the probability mass for each k possible outcome. For this distribution, the pdf value
for any x other than 1, 2, or 3 is 0.

Step 6. Compute descriptive statistics.


Compute the mean, median, and standard deviation of the distribution.
m = mean(pd)
m = 1.6667
med = median(pd)
med = 1
s = std(pd)
s = 0.7454

Compute and Plot Hypergeometric Distribution CDF


This example shows how to compute and plot the cdf of a hypergeometric distribution.
Compute the cdf of a hypergeometric distribution that draws 20 samples from a group of 1000 items,
when the group contains 50 items of the desired type.
x = 0:10;
y = hygecdf(x,1000,50,20);
Plot the cdf.
stairs(x,y)

The x-axis of the plot shows the number of items drawn that are of the desired type. The y-axis
shows the corresponding cdf values.
Linear regression models can be useful for the study of relations between two data series. Matlab
provides different commands to estimate linear regression coefficients and corresponding
statistics.
Linear regression and correlation coefficient
Least squares fit can be performed by the command regress. Assume a linear system

randn('seed',1);
x = [1:10:500]';
y = 2.5 * x + 80 + 50 * randn(50,1);

plot(x,y,'.')

and estimate the linear fit and the confidence intervals within 95% with

[b, bint] = regress(y, [ones(length(x),1), x], 0.05)


b =

78.1034
2.4832
bint =

50.3461 105.8608
2.3859 2.5805

In order to get not only an estimate for the regression coefficient, but also the offset, we added a vector
consisting of ones in the second argument of regress. The result b yields the offset 85 and the
regression coefficient 2.5, the corresponding confidence intervals are stored in bint.

hold on
plot(1:500, b(2) * [1:500] + b(1))

Residuals can be automatically computed with

[b, bint, residuals] = regress(y, [ones(length(x),1), x], 0.05);


clf, plot(residuals), ylabel('Residuals')
Sample Matlab code for linear regression using definition

n=input('Input number of data size (n):');%ask for number of data


points

for i=1:n%loop for input the data points

x(i)=input('Input x series one by one:');%take the data for x

y(i)=input('Input y series one by one:');%take the data for y

end

scatter(x,y)%make a graph of data pointfor i=1:n%loop to calculate


summition

xy(i)=x(i)*y(i);%calculate the of x*y

x2(i)=(x(i))^2;%calculate the of x square

end

sumx=sum(x);%calculate the sum of x

sumy=sum(y);%calculate the sum of y


sumxy=sum(xy);%calculate the sum of x*y

sumx2=sum(x2);%calculate the sum of x square

xm=sumx/n;%calculate the mean of x

ym=sumy/n;%calculate the mean of y

a1=(n*sumxy-sumx*sumy)/(n*sumx2-sumx*sumx)%calculate the b

a0=ym-a1*xm%calculate the a

for i=1:n%loop for 1=1 upto 9

st=(y(i)-ym)^2;%calculate the diffrence of y from mean

sr=(y(i)-a1*x(i)-a0)^2;%calculat the least squearend

sumst=sum(st);%sum of least square principle

sumsr=sum(sr);%sum of least square principle

syx=(sumsr/(n-2))^0.5;%calculate the value for least square

r2=(sumst-sumsr)/sumst

syx=(sumsr/(n-2))^0.5;

r2=(sumst-sumsr)/sumst

You might also like