Date: 24/03/2018 10:00 AM

Day: Saturday

Section Num.: (04)

 

Functions – IF - Scripts

 

  • Some of Built-in functions in matlab

 

  • Size( )

>> size(x)

ans =

  • 1

 

  • x * y' Equal to dot(x, y)

>> x = [1 2 3];

>> y = [4 5 6];

>> x * y'

ans =

    32

>> dot(x, y)

ans =

    32

 

  • Cross( )

>> cross(x, y)

ans =

    -3     6    -3

 

  • eye()

>> eye(4)

ans =

     1     0     0     0

     0     1     0     0

     0     0     1     0

     0     0     0     1

 

  • Zeros()

>> zeros(3,4);

 

  • >> Ones()

ans =

     1     1     1     1

     1     1     1     1

     1     1     1     1

 

 

  • Create New function à Home->new->function

      Note: The name of the function must be as same as the name of  the file of the function.

 

  • my_sinh( x )

function [ y ] = my_sinh( x )

    % This is a comment for my new sinh function

    y = (exp(x)-exp(-x))/2;

end

           

>> my_sinh(1)

ans =

    1.1752

 

  • Is_even(x)

function [ y ] = is_even( x )

    y = ~mod(x,2);

end

 

>> is_even([1 3 4 5 9 0])

ans =

     0     0     1     0     0     1

 

  • Solve system linear of equations

3x +   2y    –   z  =  1

2x –   2y    +  4z =  –2

–x +  0.5y  –  z   =  0

     ------------------------------------

 

>>  A = [3 2 -1; 2 -2 4; -1 .5 -1];

>> b = [1 -2 0];

>> inv(A)*b'

ans =

    1.0000

   -2.0000

   -2.0000

 

  • ssloe(A, B)

function y = ssloe( A, B )

    y = inv(A)*B';

end

 

>> ssloe(A, b)

ans =

    1.0000

   -2.0000

   -2.0000

 

  • det(A)

>> det(A)

ans =

   -3.0000

 

  • Eigenvalues and eigenvectors

>> eig(A)

ans =

    3.6295

   -3.8445

    0.2150

 

>> [V, D] = eig(A)

 

V =

   -0.9601   -0.3061   -0.3288

   -0.2098    0.9134    0.7469

    0.1847   -0.2682    0.5780

 

 

D =

    3.6295         0         0

         0   -3.8445         0

         0         0    0.2150

 

If Condition

 

  • estimate( mark, FullMark )

 

function e = estimate( mark, FullMark )

    p = mark/FullMark * 100;

    if(p>=85)

         e = 'Excelent';

    elseif(p>=75)

         e = 'Very Good';

    elseif(p>=65)

         e = 'Good';

    elseif(p>=60)

         e = 'Ok';

    else

         e = 'Fail';

    end

end

 

 

  • Determine if a value falls within a specified range.

function  isInRange( minV, maxV, V )

    if ((V >= minV) && (V <= maxV))

        disp('Value within specified range.')

    elseif (V > maxV)

        disp('Value exceeds maximum value.')

    else

        disp('Value is below minimum value.')

    end

end