Matlab Tutorials

Advanced level tutorial of some basic stuffs. It is assumed that the reader has some knowledge about basic commands in matlab.

Result generated by running the MATLAB script given below. As the number of times the the script is run to select a row we can see that the probability of choosing any row becomes equal. This means a row is chosen uniformly random without any bias on any selection. However,  there are better algorithms (compared to one given by MATLAB) to perform random selections.


Choosing two random elements from a 100 X 100 matrix.

We create a matrix and then choose two random elements for n times. See how the probability of choosing an element from particular row converges to a constant values over several selections.

%creating a sample matrix to work with
%A random array with dimensions 100X100
n=1e4; % n number of time two random matrix elements are chosen. 
% Please vary this n to generate a plot that looks like above.

% One method is two choose two random rows and then choose two random 
% columns indices for each of the already chosen ones
for i=1:n
[rows,columns]=size(M); % Gives the size of the matrix 


p=zeros(10,1); % Initializing discrete probabilities to zero.
for i=1:n
 if(y(i)<=10) p(1)=p(1)+1;
 elseif(y(i)>10 && y(i)<=20) p(2)=p(2)+1;
 elseif(y(i)>20 && y(i)<=30) p(3)=p(3)+1;
 elseif(y(i)>30 && y(i)<=40) p(4)=p(4)+1;
 elseif(y(i)>40 && y(i)<=50) p(5)=p(5)+1;
 elseif(y(i)>50 && y(i)<=60) p(6)=p(6)+1;
 elseif(y(i)>60 && y(i)<=70) p(7)=p(7)+1;
 elseif(y(i)>70 && y(i)<=80) p(8)=p(8)+1;
 elseif(y(i)>80 && y(i)<=90) p(9)=p(9)+1;
 else p(10)=p(10)+1;

p=p/n; % Normalizing the probabilites

% Upon convergence, each of the interval should have the same probability (p(1)=p(2)=..=p(n)
% and all the probabilites should sum upto 1. p(1)+p(2)+..+p(10)=1 
% This is proof of randomness. So we should see a straight line at y=0.1 in xy plot.
% See the plot above.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Powered by

Up ↑

%d bloggers like this: