Matlab Tutorials

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

tutorial_1_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
M=ones(100).*rand(100);
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 
random_row_1=int64(rows*rand());
random_row_2=int64(rows*rand());
random_column_1=int64(columns*rand());
random_column_2=int64(columns*rand());

index_1(i,:)=[random_row_1,random_column_1];
index_2(i,:)=[random_row_2,random_column_2];
x(i)=i;
end

y=double(index_1(:,1));
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;
 end
end

p=p/n; % Normalizing the probabilites
plot(p) 

% 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: