9:18 AM

Introduction to simulink

That was more or less what we need to know for basic matlab operations.Hope it helped.I will keep posting more fun facts as and when I can remember them.Please feel free to suggest,comment or discuss.I know this isn't any blog with good piece of writings...

Matlab supports a software called simulink.Simulink is where you can design various models and check the working of the systems.

You will get a shortcut for simulink in the matlab shortcut.Click it.Or you can type simulink in the command window.

The window for simulink opens .To the left you can see libraries.At the bottom you can see the block description.To the right are the various blocks for the selected blockset from the libraries.

5:39 AM

Plotting a 3-D graph

So we've learnt how to plot a 2-D graph.Now here we are to plot a 3-D graph.In this case we require three variables x,y,z.

where x,y,z are mutually dependent variables or at least one of the depends on both the other variables.

1.surf(x,y,z)
plots the surface formed by x,y and z interdependent variables.

2.meshgrid()

A. This function is used to manipulate and arrange the coordinates in a matrix form.
If you want to specify the range of x only,where y and z depends on the value of x:

x=meshgrid(-2:0.1:2);
and this will give you the 5x5 matrix with the column elements of each row being -2:0.1:2.

let's draw a parabola out of this in 3-D.Since the general equation for a parabola is y=x^2 and this is not matrix multiplication but element-by-element multiplication of x co-ordinates.for more reference:

hence:
y=x.^2; %element-by-element multiplication
z=x.^2; %element-by-element multiplication

%plotting the parabola
surf(x,y,z);
%label the axes
xlabel('x');
ylabel('y');
zlabel('z');

and you get the 3-D plot.


B.If you want to specify the range of x and y and z depends on both of them then:

[x,y]=meshgrid(-2:0.1:2,-2:0.1:2);

let's try to draw this parabola:
z=x.^2+y.^2; %element-by-element multiplication

%plotting the parabola
surf(x,y,z);
%label the axes
xlabel('x');
ylabel('y');
zlabel('z');



2.Checking the plot and playing with them:

When you get the figure,go to tools->Rotate 3-D.You will find that the cursor has changed to a spiral one.Hold the left mouse button(right-handed person) on the picture and rotate your plot to see from various directions.


3.plotting a sphere:

sphere(n)

will plot a sphere of unit radius withn-by-n faces.
eg., sphere(20)


increase the number and see the effect.You can also try meshgrid to draw a sphere of desired radius in the desired location.
PLEASE LEAVE A COMMENT :)

1:24 PM

Working with workspace

Go to file->new->M-File

Write your function and programming here.And best of luck...
PLEASE LEAVE A COMMENT :)

1:20 PM

defining a Function

A function is a programming or a part that you build and store it in the matlab saved file location.Now this function can be called by other functions or can be run by the user to check for the output.

Thus a function has the following parts:

1.The reserved word 'function'
2.The function name
3.The input variables(optional)
4.The returned values(optional).

Hence the syntax is:
function [rvar1 rvar2...rvarn]=function_name (ivar1,ivar2...,ivarm)

%the programming

end

The input variables:

The input variables are the variables that you may require for computing and manipulating purposes.Here in the syntax they are assigned to as ivar1,ivar2,...,ivarm for m variables.

The returned variables:

Te returned variables are the variables that you want to get as the output after the execution of the function.Here in the syntax they are assigned to as rvar1 rvar 2 ...rvarn fo n returned variables.

**Calling a function

You can simply write the name of the function and type in the values for the input variables in correct order and of correct number of variables(if there are any).
1.You can use it in another function hence rite it in another function.
2.You can run the function in the command window by the same method.

Here is an example where the function takes a complex number as an input and gives the absolute value and the phase value or theta of the complex number as the output.


function [absolute,theta]=to_polar(n)

absolute=abs(n)
p=angle(n);
theta=(p/pi)*180

and when you type:
to_polar(9+5i)

in the command window and run it to see the answer.
PLEASE LEAVE A COMMENT :)

9:07 AM

Falling into infinity(loops and conditions)

Well this is an album by DREAM THEATER,my favourite.What I am going to discuss here is how to write loops.As you can see that matlab is quite fun and easy to use.The syntax is not much of a problem.And if you are wrong somewhere,matlab will tell the possible reasons.Te syntax is quite flexible and if you know C,C++ or the like,matlab is 'as easy as pie'.

1.Whenever you want to start a loop you need to write 'end' at the end to denote its 'end'.Same applies for conditions also.So if you want to check if x is equal to 5 then change it to 6:

if x==5
x=6;
end

so the condition is checked here.The condition ends with an 'end'.Since you are checking if it's equal or not you are using two equal(=) signs.(One equal sign(=) would mean that you are assigning the value of x already-True for C,C++ not for matlab).Matlab will show an error.lets do the above case again:

if x=5
x=6;
end  %this will show an error

and if you have more than one conditions so do it like this:

if x==5
%statement;
elseif x==6
%statement;
end

2.for loop:

the syntax is:

for var=i:j:k
%statements;
end

var stands for a variable name.
i=starting value
j=increment
k=stop value

If no value is given for j then by default it is taken to be 1.

eg., for i=1:2:10
i
end
gives the answer:

i =

     1


i =

     3


i =

     5


i =

     7


i =

     9
3.while loop:

the syntax is:
while (condition)
%statements;
end

while loop executes until the condition is false whereas for loop executes until the variable name reaches the stop value.
eg.,

while i<5
i=i+1
end

gives

i =

     2


i =

     3


i =

     4


i =

     5
PLEASE LEAVE A COMMENT :)

4:44 AM

Matrix operation

1.If you want to add/subtract two matrices just adding them will do provided they are of same dimensions.
eg.,

a=[1 2;3 4];
b=[5 6;7 8];

 c=a+b gives

c =

     6     8
    10    12

2.Multiplying two matrices can also be done in a similar way so is dividing one matrix by another.
eg.,
c=a*b %provided num_of_columns of a=num_of_rows of b
gives

c =

    19    22
    43    50
 and for division
c=a/b %this is actually a*inverse(b)
gives you
c =

    3.0000   -2.0000
    2.0000   -1.0000

3.In fact you can solve linear equations using matrix form.This can be done by Martin's rule.eg.,
if the three equations are-
6x+8y+z=8;
4x+7y-5z=5;
10x+6y-9z=14;

if the equation can be represented as AX=B where A=[6 8 1;4 7 -5;10 6 -9]

A =

     6     8     1
     4     7    -5
    10     6    -9
i.e.,the coefficients of the variables and X=x
                                                                y
                                                                z
and B=8
           5
           14
then the solution can be found out by Martin's rule:X=B.inverse(A)
so if you type X=B/A gives you the desired solution:

X =
    2.7472   -2.5843    0.1854

4.However if you want to do element-by-element operation you need to do a little variation.

Suppose you want to square each number of a matrix x=1 2
                                                                                      3 4

simply doing x^2 will multiply the whole matrix with itself.Hence for element-by-element operation you need to do the following

>> x.^2

The dot(.) signifies element-by-element operation.So if you want to divide one matrix by another element-by-element simply write
x./y.Therefore the dot(.) must appear before every operational sign.


5.Transpose of a matrix.
X' gives you the transpose of the matrix X.
PLEASE LEAVE A COMMENT :)

5:53 AM

THE MOST IMPORTANT OF ALL

It's good to see that everyday someone or the other person is having a look at my programmings.I am taking exams so I apologize for not posting any more programmings or tutorials.I will surely do that after my exams are over.But please don't stay silent.Say,suggest,comment or discuss anything you like.I would really be happy.I shall be posting more interesting stuffs I have learnt.But I need your help.

SUGGEST,COMMENT OR DISCUSS ANYTHING SO THAT I CAN KNOW THAT MY PROGRAMMINGS ARE HELPING YOU, OR MAY BE NOT...

10:26 AM

MID-POINT RULE

A friend from yahoo answers asked me to write this program.So here it is:


function mid_point_rule

F=input('enter the function: ','s');
F=inline(F);

a=input('Enter the lower limit: ');
b=input('Enter the upper limit: ');
n=input('Enter the number of rectangles to be used(even number): ');

del_x=(b-a)/n;

sum=0;
for i=1:n
    x1=a+i*del_x;
    x0=a+(i-1)*del_x;
    x_mean=(x1+x0)/2;
  
    sum=sum+F(x_mean);
end
integ=del_x*sum;
fprintf('\nHence the integration is %d\n',integ);


Main formula:


Midpoint Rule:
where,






PLEASE LEAVE A COMMENT :)

12:35 PM

plotting poles and zeros of a z transform

function poleszeros

%G(z)= (4z4+5.6z3+6z2+2.4z-6.4)/(3z4+2.4z3+6.3z2-11.4z+6)

num=[4 5.6 6 2.4 -6.4];
den=[3 2.4 6.3 -11.4 6];

z=roots(num)
p=roots(den)

pzmap(p,z)
grid on;
PLEASE LEAVE A COMMENT :)

12:24 PM

DFT of an exponentially discrete signal

function ndft()
%plots the frequency and phase spectrum of N samples of the signals

M=20; %no. of samples taken to plot each sample of the fequency and phase spectrum
N=40;
n=1:M;
x(n)=(0.5).^(n-1);
x(M+1:N)=0;

y(1:N)=0;

for k=1:N
    for n=1:M
        y(k)=y(k)+x(n)*exp(-j*2*pi*(k-1)*(n-1)/N);
    end
end

k=0:N-1;
subplot(3,1,1);
stem(k,x(k+1));
title('input');
subplot(3,1,2);
stem(k,abs(y(k+1)));
title('frequency spectrum');
subplot(3,1,3);
stem(k,angle(y(k+1)));
title('phase spectrum');
      


CHANGE THE VALUE OF N AND SEE THE DIFFERENCE

PLEASE LEAVE A COMMENT :)

12:01 PM

Plotting the frequency and phase response(DFT) of a discrete signal

function ndft()
%plots the frequency and phase spectrum of N samples of the signals

M=10; %no. of samples taken to plot each sample of the fequency and phase spectrum
A=input('Enter the magnitude ');

N=100;
n=1:M;
x(n)=A;
x(M+1:N)=0;

y(1:N)=0;

for k=1:N
    for n=1:M
        y(k)=y(k)+x(n)*exp(-j*2*pi*(k-1)*(n-1)/N);
    end
end

k=0:N-1;
subplot(3,1,1);
stem(k,x(k+1));
title('input');
subplot(3,1,2);
stem(k,abs(y(k+1)));
title('frequency spectrum');
subplot(3,1,3);
stem(k,angle(y(k+1)));
title('phase spectrum');

PLEASE LEAVE A COMMENT :)

8:10 PM

plotting a 2-D graph

I am bit under pressure cause our exams are banging at the door...lolz...However I thought of showing how to plot graphs.

1.ezplot('f(x)',[min max])

plots the given function within the range [min,max]

2.plot(x,f(x)) plots the given function y=f(x)

However in this case you need to use discrete values to define the range of x.
eg.,
n=0:0.1:2*pi;
plot(n,sin(n))

you can also write plot(f(x)) and produce the same result.In the above example matlab plots a sinusoidal graph by evaluating sin n for each value of n.n here is a range of discrete values with difference of 0.1.Hence in order to get a more continuous graph decrease the difference of n.Try It!

Now if you want to plot more than one graphs on one figure then use hold function.And if you want to get a better view of the graph use grid function.

Labels:

When you want to label the axes and the graph then use xlabel('name1'),ylabel('name2'),title('Title') functions.

Here's an example:


n=0:0.01:1;
grid on;
plot(5*n);
hold on;
plot(exp(n),'red')
hold off;
grid off;
xlabel('x->');ylabel('Amplitude');title('Overlapping graphs');

3.stem(n,y(n))

Sometimes we want to plot discrete values.This function plots the discrete values n points and their corresponding values.
PLEASE LEAVE A COMMENT :)

11:33 AM

Input and Output(edited)

1.Suppose we want the user to give an input.This we do using the following format:

x=input('statement' );
where x is assigned the input value.Here x is a real number.

Sometimes we want the user to give an input that may be some character or any string.In that case we use the following format:

x=input('statement','s');
Here x is assigned the character or string value.And this is indicated by 's' which stands for string type.

2.We have already seen a few examples where we want to produce some numerical output.However in case of some string we use the sprintf() or disp() function.
      eg.,
           sprintf('I know matlab')
or disp('I know matlab')
or frpintf('I know matlab')
gives the output:
ans=

I know matlab

3.Now suppose you want to display a value of any variable within a statement you can this as follows:
eg.,
i=5;
fprintf('the value for i is %d',i);

Here the output goes like this:
the value of i is 5
thus the %d is replaced by the value of i.Now if there are more than one variables then it's nothing different from the previous example:
eg.,
i=5;
j=8;

fprintf('%d is greater than %d',j,i);

Here the first %d is replaced by j and the second %d is replaced by i.Hence the output is:
8 is greater than 5

4.If you want to add a new line or a tab or a carriage return use the following symbols inside the fprintf function:
\n for new line,i.e.,goes to the next line and places the cursor at the beginning.
\t for a tab
\r for a carriage return,i.e., returning the cursor to the intial position of the row.

eg.,
if you want to display:

what is this?
i don't know

do it like this:

fprintf('what is this?\ni don't know\n');

The \n moves the cursor to the new line and prints the next words from the fresh start.
PLEASE LEAVE A COMMENT :)

6:26 AM

products and expansions

1.If there are algebraic functions which are needed to be multiplied,then simply writing the expressions and pressing enter won't give you the answer.Rather it will show the same as the input.

Solution:-
Firstly you have to define the variables and for finding out the product of two expressions we will use the function expand().
       eg.,
              >> syms x y
              >> expand((x+y)*(x-y))
gives you

ans =

x^2-y^2

2.Now in order to factorize an algebraic expression we use the function factor()
   eg.,
         >> syms x y
         >> factor(x^2-y^4)
gives you
ans =

(x-y^2)*(x+y^2)

3.Lastly in order to find out the quotient when an algebraic expression is divided by another, we use the simplify() function.

   eg.,>> simplify((x^3-y^3)/(x-y))

The solution is :
ans =

x^2+x*y+y^2
But in order to get any expression in its simplest form we use simple() function sometimes.

  
    
PLEASE LEAVE A COMMENT :)

10:34 AM

solving equations

Here we are now going to solve equations.

1.Solving an equation with one variable:
 solve('equation') will solve the equation(linear or non-linear) for the given variable.
         eg., solve('5*x+x^2=9') gives the answers

                      -5/2+1/2*61^(1/2)
                      -5/2-1/2*61^(1/2)
2.Solving equations with more than one variables
    eg.,simultaneous equations with two variables x,y
      [x,y]=solve('equation_1','equation_2')
                        This solves the two equations(linear or non-linear). two the results of the two variables.If there are more than one solutions for each variable,eg.
x=
       5
       6
y=
       7
       8
           then (5,7) and (6,8) are the two solutions of the equations.

3.Expressing one variable in terms of the other:
solve('equation','subjective variable')

eg. solve('5*x-1=y','x') expresses x in terms of y
   therefore the  solution is:

ans =

1/5+1/5*y
                                                   


PLEASE LEAVE A COMMENT :)

9:57 AM

the symbol 'pi'

             If we execute sin (pi) we should get zero as the answer,however the value of sin(pi) when executed in matlab shows a value of 1.2246e-016.The reason is that pi here is not the irrational number rather an approximate value of    3.141592653589793.

             Hence in order to use the irrational value of pi we have to execute it as a symbol.
sin(sym('pi'))
                     This gives a value of zero.This is so because pi here is treated as a symbol which has the irrational value.It should be written as sym('pi').
              
PLEASE LEAVE A COMMENT :)

1:55 PM

basic things

here we shall start learning matlab from the basic stuffs.

1. n=0:10
               This means that n is a one-dimensional array or a row matrix with values taking from 0 to 10 with an interval of 1,i.e.,[0 1 2 3 ... 9 10]

2.n=0:0.5:10
                This means that n is a one-dimensional array or a row matrix with values from 0 to 10 with an interval of 0.5,i.e.,[0 0.5 1 1.5 ... 9.5 10]

3.use of a ;
                 If we put a semicolon at the end of an equation or an expression matlab does not display the resulting values.And if we want to see the values we DO NOT  put a semicolon.

4.x(n)
          x(n) is an array of n elements under the family named x.each number in the array is allocated an address but the address starts from 1 and ends at n.So lets do a program that allocates values to the array x(n) to each address.

n=1:10;
x(n)=n;

 This program stores the value n at each of the nth address of the array.
Therefore x=[1 2 3 4 5 6 7 8 9 10]

So if you wanna see the values allocated to the array do either of the following:

1.Remove the ; from the second line of the above programming.
2.Type x and press enter in the command window.

Now if you wanna see the value stored at the address location 5 simply type x(5) and press enter.See the result.

5.syms
          This is used to initialize a variable or variables as a symbol or symbols.

           syms x y indicates x and y are initialized as symbols or variables.

6.whos
           Executing this shows all the variables used,the space allocated to them,the class.If you wanna clear a variable name so type clear x if you wanna clear x.if u wanna clear two variables x and y execute clear x y.
If you wanna clear all type clear all
          

PLEASE LEAVE A COMMENT :)

8:26 AM

sampling and similarities

we all know cos x is periodic with a period of 2*n*pi.so if two signals are sampled at a rate less than the Nyquist rate then we can have same samples from two different signals.The reason is as follows:

lets say sampling frequency is Fs.Hence Ts=1/Fs.
if a signal say cos(2*pi*f*t) is sampled then we get the sampled version as cos(2*pi*F*n*Ts)

now lets take another signal cos(2*pi*(f+Fs)*t).If this is sampled at the same rate then we get:
cos(2*pi*(f+Fs)*n*Ts)=cos(2*pi*f*n*Ts+2*pi*Fs*n*Ts) now the term 2*pi*n*Fs*Ts yields nothing but 2*pi*n.Since cos x is periodic with period 2*pi*n hence the second sampled signal reduces to cos(2*pi*f*n*Ts) which is the same sampled signal as the previous one.

PROBLEM :
 Four sinusoidal signals are sampled and they are found to have same sampled version in pairs.Now you know why.


function sinseq1()

A=2;
phi=0;
n=0:10;

%case 1
x=A*cos(2*pi*1.1*n+phi);
subplot(2,2,1);
stem(n,x);

%case 2
x=A*cos(2*pi*0.9*n+phi);
subplot(2,2,2);
stem(n,x);

%case 3
x=A*cos(2*pi*0.8*n+phi);
subplot(2,2,3);
stem(n,x);

%case 4
x=A*cos(2*pi*1.2*n+phi);
subplot(2,2,4);
stem(n,x);


PLEASE LEAVE A COMMENT :)

2:20 AM

this is the ramp function

function rmps()
f=input('enter the sample frequency= ');
l=input('enter the length of the sequence= ');

Ts=1/f;
n=1:l;
x(n)=n-1;

n=0:l-1;
stem(n*Ts,x,'fill');
title('ramp function');
xlabel('time in secs');
ylabel('amplitude');


given is the example for sample frequency 25000 and sample length 40.

PLEASE LEAVE A COMMENT :)

2:18 AM

unit step sequence

here's another one

function usts()
f=input('enter the sampling frequency= ');
l=input('enter the length of the sequence= ');

Ts=1/f;
n=1:l;
x(n)=ones(1,numel(l));
n=0:l-1;
stem(n*Ts,x,'fill');
title('unit step sequence');    
xlabel('time in secs');
ylabel('amplitude');
  
PLEASE LEAVE A COMMENT :)

2:12 AM

unit sample sequence

i started off with simple programs and i will keep posting them...any queries and suggestions are always welcome :)

this is the first programming i did-unit sample sequence
pretty easy...

function uss1()
N=input('enter the sampling frequency = ');
l=input('enter the length of the sequence = ');

Ts=1/N;
x(1)=ones;
 for n=2:l
     x(n)=zeros;
 end
   n=0:l-1;
   stem(n*Ts,x,'fill');
   title('unit sample sequence');
   xlabel('time in secs');
   ylabel('amplitude');

there r a lot more ways of doing this programming...thanks for reading :)

PLEASE LEAVE A COMMENT :)