Search This Blog

Monday, October 3, 2011

Basic of MATLAB and programming for aerospace engineering


Matlab: Matrix Laboratory
Matlab is both a computer programming language and a software environment for using language effectively.
Matlab has a number of add-on software modules, called toolboxes, that perform more specialized computations, dealing with applications such as
Image and signal processing
Financial analysis
Control systems design
Communication systems
Fuzzy logic
Neural networks
Filter design
Optimization
Partial differential equations
Statistics
System identification
Virtual reality
Wavelet
content:
Matlab Windows and Menus
Basic Operations and Arrays
Files, Functions
Plotting with Matlab
Programming with Matlab
Numerical Methods for Differential Equations
 let's to practice some example's :
Matlab
         Enter commands and expressions at the prompt position (>>) in command window.
         Ex: r = 8/10
         Matlab supports many mathematical functions, most of which are used in the same way you write them mathematically.
         abs(x) Absolute value |x|
         sign(x) Sign, returns −1if x<0, 0 if x =0 ,1if x>0
         exp(x) Exponential
          log(x) Natural logarithm ln(x)
         log10(x) Common (base 10) logarithm
         sqrt(x) Square root
         rem(x,y) Remainder of x/y. For example, rem(100,21) is 16. Also called the modulus function.
         Row  vector
         >> r = [2,4,10];
         >> n = [2,4,10]
         n = 
                     2 4 10
         >> n = [2 4 10]
         n =
                     2 4 10
         Column  vector
         >> r = [2; 4;10]
         r =       2
                     4
                     10
         >> y = [ 2 4 10]’
         y =      2
                     4
                     10

         Ex: r =[ 2 4 10]
         >> v = 5*r
         v = [10 20 50]

         >>w = r + v
         w = [12 24 60]

         >> u = [r, w]
         u = [2 4 10 12 24 60]

         Ex: Creat a row vector from 5 to 30, incremented by 0.1.
         >> t = [5:0.1:30]
         t = 5, 5.1,5.2,…, 29.8,29.9,30.


         Matrix
         >> a = [2,4,10;16,3,7]
         a =
                     2  4  10
                     16  3  7

         >> A = [6, -2;10,3;4,7], B = [9,8;-5,12];
         >> A*B
         ans
                     64        24
                     75        116
                     1           116

·         Array operations
·         Ex: a =[1:5]; b = [3:7];
·         >> a = [1:5]
·         a =
·         1          2          3          4          5
·         >> b = [3:7]
·         b =
·         3          4          5          6          7

·         >> c = a .* b
·         c = 3   8          15        24        35

·         >> c = a ./ b
·         c = 0.333   0.5   0.6   0.667 0.7143

·         >> c = a .^ b
·         c = 1   16   243          4096   78125


         Two special functions in Matlab can be used to generate new vectors containing all zeros or all
         ones.
         zeros(m,1) Returns an m-element column vector of zeros
         zeros(1,n) Returns an n-element row vector of zeros
         ones(m,1) Returns an m-element column vector of ones
         ones(1,n) Returns an n-element row vector of ones
         Examples:
         >> x = zeros(3,1)
         x=
         0
         0
         0
         >> y = ones(1,3)
         y=
         1          1          1
         Basic Operations and Arrays
         Ex:
          
          >> x = [0:0.01:1];
         >> y = exp(-x) .* sin(x) ./sqrt(x .^2 +1);
         >>plot(x,y)
Matrixes and arrays
         > >f=[ 123 ;456 ]
         f=
         123
         456
         > >g=f ’ %transpose %
         g=
         14
         25
         36

         >> x = 0:4;
         >> y = 5:5:25;
         >> A = [x’ y’]
         A=
         05
         11 0
         21 5
         32 0
         42 5
         > >A=[ 123 ;456 ]
         A=
         123
         456
         >> s = size(A)
         s=
         23
         >> [r,c] = size(A)
         r=
         2
         c=
         90
         3
         >> r = size(A,1)
         r=
         2
         >> c = size(A,2)
         c=
         3


Files and Functions
         Matlab uses two types of M-files: script files and function files.

         A script file contains a sequence of Matlab commands and is useful when you need to use many commands or arrays with many elements.
          
         A function file is useful when you need to repeat a set of commands several times.
         Example of a simple script file computes the matrix C=AB  and displays it on the screen.
         % Program ‘prod_abc.m’
         %This program computes the %matrix product C = A  * B,and %displays the result.
         A=[1,4;2,5];
         B=[3,6;1,2];
         C=A*B
         In the Matlab command window type the script file’s name prod_abc to execute the program.
         >>prod_abc
         C=
         7   14
         11 22
         Function file: All the variables in a function file are local, which means their values are available only within the function. Function files are useful when you need to repeat a set of commands several times. Its syntax is as follows:
         function [output variables] = function_name(input variables);
         Note:  
         (i) output variables are enclosed in square brackets, the square brackets are optional when there is only one output.
         (ii) input variables are enclosed with parentheses
         (iii) function_name must be the same as the filename in which it is saved (with the .m extension)
         (iv) function is called by its name.
         Ex:               , find the value of x that gives a minimum of y for            .
         function y=f2(x)
         y=1-x .* exp (-x);
         Save it as f2.m
         In command window, type x=fmin(‘f2’, 0, 5). The answer is x = 1. To find the minimum value of y, type y = f2(x).


         XY plotting functions
         Ex:       >>x = [0:0.1:52];
                     >>y = 0.4*sqrt(1.8*x);
                     >>plot(x,y)
                     >>xlabel(‘Distance (miles)’)
                     >>ylabel(‘Height (miles)’)
                     >>title(‘Tocket height as a function of downrange distance’)

         The function plot command fplot
         Syntax
         fplot(‘string’,[xmin  xmax])
         or
         fplot(‘string’,[xmin  xmax  ymin  ymax])
         Ex:       >> f = ‘cos(tan(x))-tan(sin(x))’;
                     >>fplot(f, [1 2])

Plotting with Matlab
         Ex: plot the hyperbolic sine and tangent
         x = [0:0.01:2];
         y = sinh(x);
         z = tanh(x);
         plot(x,y,x,z,’- -‘), xlabel(‘x’), …
         ylabel(‘Hyperbolic sine and tangent’),…
         legend(‘sinh(x)’, ‘tanh(x)’)

         Data markers, line types and colors
         Data markers: .  *  x  o  +
         Line types: -  --  -.  :
         Colors: black(k)   Blue(b)  Green(g)   Red(r) Yellow(y)

         Surface mesh plots (z=f(x,y))

         [X,Y]=meshgrid(x,y), if x=[xmin:xspacing:xmax], y=[ymin:yspacing:ymax]

         The meshgrid function generates the grid point in the xy plane, and then evaluate the function f(x,y) at these points.
 

         Ex:                                                                                                      with a spacing of 0.1.

         >>[X,Y]=meshgrid(-2:0.1:2);
         >>Z=X.*exp(-((X-Y.^2).^2+Y.^2));
         >>mesh(X,Y,Z), xlabel(‘x’), ylabel(‘y’),zlabel(‘z’)



         Contour plots
         Ex:
         >>[X,Y]=meshgrid(-2:0.1:2);
         >>Z=X.*exp(-((X-Y.^2).^2+Y.^2));
         >>contour(X,Y,Z), xlabel(‘x’), ylabel(‘y’)

Programming with Matlab
         Relational operators
         <            less than
         <=       less than or equal to
         >                   greater than
         >=       greater than or equal to
         = =      equal to
         ~=       not equal to
         Logical operations
         ~                    not
         &                    and
         |                       or
         xor(a,b)           exclusive or

Conditional statements
(1)       if   logical expression
                               statements
     end

Ex: if x >= 0
                        y = sqrt(x)
            end
            or it can be written on a single line
            if x >= 0, y = sqrt(x), end


(2) Nest if statements
                        if logical expression 1
                               statement group 1
                        if logical expression 2
                                    statement group 2
                        end
                        end

Nested if Statements
         if statements may be nested, as shown in the following example:
If d<5 0
            count = count + 1;
            disp(d);
            If b>d
                        b=0 ;
            end
end


(3) The else statement
                        if logical expression
                                    statement group 1
                        else
                                    statement group 2
                        end

Ex:
    if  x >= 0
                        y= sqrt(x)
            else
                        y = exp(x) – 1
    end

(4) The elseif statement
            if  logical expression 1
                        statement group 1
            elseif  logical expression 2
                        statement group
            end

Ex: y = lnx  if x >= 5,  y = sqrt(x)  if 0<= x < 5
            if x >= 5
                        y = log(x)
            elseif x >= 0
                        y = sqrt(x)
            end


Loops

for loop variable = m:s:n
                        Statements
end

m:s:n=>initial value m, incremented by the value s and terminated by the value n.

Note: s may be negative, k=10:-2:4 produce k = 10,8,6,4. if s is omitted, the step value defaults to one.
While loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance.

while logical expression
            statements
End

Ex:
x = 5;
while x <25
                        disp (x)
                        x = 2*x-1;
end
The results displayed by the disp  statement are 5, 9, and 17.

For the while loop to function properly, the following two conditions must occur;

         The loop variable must have a value before the while statement is executed.
         The loop variable must be changed somehow by the statements.


Ex: implied loops
x= [0:5:100];
y = cos(x);

To achieve the same result using a for loop, we must type

for k = 1: 21
                        x = (k-1) *5;
                        y(k) = cos(x);
end



Switch structure:
Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structures.


switch input expression (scalar or string)
                        case value1
                                    statement group 1
                        case value2
                                    statement group 2
                       
                        otherwise
                                    statement group n
end



Ex: variable angle
            switch angle
                        case 45
                                    disp(‘Northeast’)
                        case 135
                                    disp(‘Southeast’)
                        case 225
                                    disp(‘Southwest’)
                        case 315
                                    disp(‘Northwest’)
                        otherwise
                                    disp(‘Direction Unknown’)
    end

         Consider writing a user-defined function that searches a matrix input argument for the element with the largest value and returns the indices of that element.
         function [r,c] = indmax(x)
         % INDMAX returns the row and column indices of
         % the maximum-valued element in x
         [m n] = size(x);
         xmax = x(1,1);
         r=1; c=1;
         for k=1:m
for l=1:n
            if x(k,l)> xmax
                        xmax = x(k,l);
                        r=k;
                        c=l;
            end
end
         end





         Testing this function:
         >> A=3; B=[2 4 3]; C=[3 2; 6 1];
         >> [r c]=indmax(A)
         r=
         1
         c=
         1
         >> [r c]=indmax(B)
         r=
         1
         c=
         2
         >> [r c]=indmax(C)
         r=
         2
         c=
         1




  

No comments:

Post a Comment