Tag Archive: Matlab


Lesson 6- Plotting

  1. Basic plotting
  2. x=11
    y=-3
    z= 3x + y.^2
    doc plot
    plot (z,x, 'o') %all points are represented by symbol o. type help plot to see all the other formatting that you can use
  3. Use ezplot() to plot sinh(x). i.e 
  4. ezplot ('sinh (x)')
    ezplot ('(e.^x)- (e.^(-x))')
  5. The script below will allow you to use various commands to fit a certain type of data.
    • subplot to plot two graphs next to each other
    • fplot fo curve fitting
    • labelling and plotting graphs using xlabel, ylabel, gtext, grid, axis, legend
    • retrieve data from a graph using ginput
    • plot polar coordinates and fit polar coordinates using ezpolar
    • finally use inline to make scripts faster
    %==========================================================================
    % Clear up workspace! -----------------------------------------------------
    clear;
    %==========================================================================
    x= [1:1:100]; %data
    y = x.^4;
    plot(x,y);
    hold %holds the current plot
    z= x.^5; plot(x,z) %overlays the plot of z on x
    close all %close all figure windows
    % creating horizontal and vertical subplots--------------------------------
    %horizontal subplot
    subplot(1,2,1), plot(y); % represents the number of plots and their position (x,y,position).i.e in this case shows two graph side-by side.
    subplot(1,2,2), plot(z);
    user_entry = input('Break Task A'); %Break point
    
    %vertical
    subplot(2,1,1), plot(y);
    subplot(2,1,2), plot(z);
    user_entry = input('Break Task A'); %Break point
    close all %close all figure windows
    % fplot-fitting set of data to form a smooth curve--------------------------------------------------------------------
    fplot('[x^4, x^6]',[0:10])
    user_entry = input('Break Task A');
    close all
    
    % using plot to show multiple lines.
    plot (x,y,'b-',x,z, 'r-');
    xlabel('x');
    ylabel('y');
    title('figure 1');
    legend('data1', 'data2', 2);
    grid on; %shows the grid
    gtext('A') %slick of the mouse on the graph will paste the word A on it
    user_entry = input('Break Task A');
    
    % getting data from the graph
    grid on
    [xin,yin]=ginput(10); % have to click mouse 10 times and it will store x and y values in xin and yin respectively
    plot(xin,yin, 'rX') % plots xin and yin with a red X
    user_entry = input('Break Task A');
    
    %using polar coordinated------------------------------------------------------
    theta = [0: pi/10: pi/2];
    rho = cos(theta).^2;
    polar(theta, rho);
    user_entry = input('Break Task A'); %Break point
    
    %using fplot equivalent- ezpolar
    ezpolar('cos(t)^2', [0,pi/2]); %equivalent of fplot
    user_entry = input('Break point');
  1. Simple SUM function files
  2. function[sum4]=mySum4(a1,b1,c1,d1) % to call the function, you have to write mySum4 (2,3,4,5) and it will return what sum4 is represented by sum4=a1+b1+c1+d1; 
  3. Simple Mutiplying Function
  4. function[sum,difference,product,ratio]=myOperations(a2,b2) % calling the function in the command window to compute myOperations on TWO mumbers will return its sum, difference, product and ration 
    sum=a2+b2; % individually define what each part of the function means
    difference=a2-b2;
    product=a2*b2;
    ratio=a2/b2;
  5. Creating a list of numbers
  6. function[x]=makeList(first,last,spacing)
    i=1;
    while first<=last % execute while in the range
      x(i)=first; % x(1)= what the user puts as first value
      first=first+spacing; % reassigns first with new value
      i = i+1; % so that x(2)=newly reassigned first
    end

Matlab is capable of much more than 2+2. It can write powerful scripts that can compute large amount of data.

  1. Simple Script– Create a new matlab script (.m) file. Press CTRL
  2. for i=1:10 % doesn't not necessarily have to be i. we just assigning it that so that. This basically repeats whatever we write next (10) time
      disp ('it works') % displays it works for (10) times
    end % for loop always have an end so it can start again and assign i=2 and do the loop for the 2nd time
    cd % displays your working directory 

    now save it by clicking the play button in the “editor” window.
    assign is a name and see the results in the command window.
    OR save it using the save button and run is from the command window by pressing

    run ('x')  % x is your filename
  3. Dice Throw– Create a new matlab script (.m) file. Press CTRL. Simulates the throw of two dice using the rand() function and returns the individual and combined score
  4. %%"dice throw" jignesh Kerai. 29/01/09. Ver 1.0
    %displays sum of two dice throws.
    %numbers are random
    %%start
    disp ('----------------------Throwing Two Dice-------------------')
    a=ceil(6*rand); % rand gives random decimal point values between 1 & 0
    b=ceil(6*rand); % ceil rounds of the 6*rand to give simulate 6 possible outputs (1-6)
    total= (a+b);
    disp ('First Dice'), disp(a); % displays First Dice and the value of (a)
    disp ('Second Dice'), disp (b);

    Now if you wanted to tell the script to double the score if both dice have the same number (i.e a=b)

    if(a==b) %placing and condition to do something if a=b. Note the double ==.
      disp('Double Score'),disp(total*2) % displays double score and 2*total value.
      else %otherwise if a is NOT = b
      disp ('Total Score'), disp(total)
      disp('##########################################################') %for fun
    end %END
  5. Real Draught Problem- Calculating the stability of a cuboid immersed in a fluid
  6. %%"Draught of a Floating" Jignesh Kerai 29/01/09
    %Determines whether a cuboid will float or not
    l=input ('what is the lenght of the cuboid (metres)?'); ';' suppresses output, i.e the output of the calculation will not be displayed in the command window
    w=input ('what is the width of the cuboid (metres)?');
    h=input ('what is the height of the cuboid (metres)?');
    pc=input ('what is the density of the cuboid (kg/m^3)?');
    pfluid=input('what is the density of the fluid (kg/m^3)?');
    
    if (pc>pfluid);
      disp('Cuboid will drown'); % if density of cuboid> fluid's density then it warns the user.
      elseif (h>l||h>w);  %elseif has to be used if you want another "if" statement within the original if loop
      disp ('Cuboid unstable') % if the height> length OR (|| height > width then disp()
      elseif (h<l||h<w);
      disp ('Cuboid is stable')
    end
    
    V= (l*w*h); % calculate volume
    m=(pc*V);
    d=(m/pfluid);
    disp('Volume='),disp(V)
    disp('mass='),disp(m)
    disp('draught='), disp(d)
    disp('------------------------------------------------------')
  7. Play Rock, Paper Scissor with the Computer
  8. %%"dice throw" jignesh Kerai. 29/01/09. Ver 1.0
    %Play Rock, Paper Scissor with the Computer
    %%start
    a= input ('choose ROCK(1), PAPER(2) or SCISSOR(3)'); % user input of what they choose
    b= ceil(3*rand); creates random numbers from 1 TO 3
    if (a==b) %Condition
        disp ('ITS A DRAW')
        elseif (a==1 && b==2) % elseif if used within an if statement to say IF again if the first if was not satisfied. && is the AND function. (i.e if a=1 AND b=2 the disp (...))
        disp ('The computer choose PAPER and you choose ROCK. PAPER covers ROCK. You LOOSE')
        elseif (a==2 && b==1)
        disp ('The computer choose ROCK and you choose PAPER. PAPER covers ROCK. You WIN')
        elseif (a==3 && b==1)
        disp ('The computer choose ROCK and you choose SCISSOR. ROCK breaks SCISSORS. You LOOSE')
        elseif (a==1 && b==3)
        disp ('The computer choose SCISSORS and you choose ROCK. ROCK breaks SCISSORS. You WIN')
    end
    a=input ('do u want to play again. YES(1), NO(2)?'); % user input
    if a==1;
        run 'C:\%location of file\FILENAME.m%' % Allows user to play again with the computer. if unsure what directory you have saved the file. use the CD command.
    else disp ('GoodBYE')
    end
    %%END--------------------%%
  9. Simple counting loop with FOR
  10. %%Jignesh
    %simple Counting loop
    a=input('enter digit to start counting from'); %starting value you want to count from
    b=input ('enter digit to stop counting'); % end
    disp ('---')
    for i=a:b
      m(i)=i; % assigns first row, first element
    end
    %%END--------------------%%
  11. Calculate Factorial of a Number-FOR
  12. a=input ('Value of n! enter your value of n') % input of last number
    f=1 %have to set value of first f
    for i=1:a %number of time whatever you write under for has to be executed
        f=f*i % first time, i=1, f=1, therefore new f=1.
        %2nd time, i=2, f=1, therefore new f=2
        %3rd time, i=3, f=2, therefore new f=6...etc
    end
    disp (f)
  13. Calculate Factorial of a Number-WHILE
  14. %%computing factorial using while loop.Jignesh%start
    n=input ('value of number to calculate factorial of') %last number
    i=1 % set value of i
    a=1% set value of a
    while i<=n % if i less than or equal to (user input) do the following
         a=a*i % first time a=1, i=1, new a =1.
         i=1+i % have to change value of i (same as for loop that automatically updates the value of i)
    end % so when it gets here, it will start the while statement again, i<=n.
        %2nd step i=2 and a=2.
        %3rd step i=3 and a=2*3= 6.
        %it will keep running till i=n.
    disp (a)
  15. Checking if input is a Prime number
  16. %%computing factorial using while loop.Jignesh
    N=input('put the number you would like to check')
     flag = 0 %add a variable called flag which assumes N is a prime
    for i=2:N-1 % for every number from 2 to n-1 divide N by each number
    x=mod(N,i);% check to see if you can divide N by i cleanly (to give an integer)
               % if it is possible to divide cleanly then x will = 0
               % if x=0 then you can divide N cleanly by another number. Hence it is not a prime
       if (x==0) % Make flag 1 to tell the rest of the code that this number is not a prime
          flag = 1
       end
    end;%after trying divide n by every number if the flag = 0 then n is a prime
        %otherwise n is not a prime
    if (flag==1)
       disp('this number is not a prime')
       else
       disp(' this number is a prime')
    end
  17. Listing all prime numbers
  18. n=1
    while (n>0); %while n is greater than 0 run the commands below
      while (isprime(n)==1) %isprime is an predefined matlab script. type help isprime or doc isprime to see how it works. alternatively i you can also see the isprime script by typing edit isprime
      disp(n)
      break; % stops the while loops. i.e it runs it once only to check if n is prime or not
      end
    n=n+1;% increases the value of n by 1 and tests if that number is prime
    end
  19. Creating multiplication tables
  20. %%create Multiplication tables for the products of all integers from
    %%1:10.and display in a 2-d array
    %%jignesh
    for i=1:10;
        for j=1:10
            table(i,j)=i*j;
        end
    end
    disp (table)
  21. Calculating the value of pi
  22. %%Calculating pi
    %Jignesh
    N=input ('Value of N?'); %number of iterative processes
    count = 0;
    for i=1:N
        x=2*rand-1;
        y=2*rand-1;
         if ( (x^2 + y^2)<1 )
            count= count + 1;
         end
    end
    pi=(4*count)./N

size (a) = b % this will return the size of array (a) in terms of Number of rows and columns and assign in to array (b). therefore b(1,1)= number of rows of (a) and b (1,2) is the number of columns of (a)
save ('abcd') % this will save the current workspace under abcd.mat filename. this function is not particularly helfull when you are a beginner but when you will have to write scripts and you will have to clear workspaces within the script and call it back to do another function the it will dawn upon you why you have save. For now you can simply go to the save button in the workspace window and save the workspace if you wish
disp (a) % displays the elements of array (a)

You can assign each element of an array (e.g A) to a particular number. It follows the same convection of mapping elements in an array. E.g

A(1,1)=22 % assigns the first row, first column with the value of (22)
A(33,44)=55 % assigns the (33rd) row, (44th) column with the value (55) and anything in between (e.g A(2,2) will be assigned zero)
A(3,1:3)=[22 33 44] % Assigns the (3rd) row, 1st to 3rd columns with values of 22,33,44
A(row,column) % e.g if row=1 and column=3 then when you type this command then it will return the A(1,3) value of the array
A(2,:) = [1:0.4:10] % auto assigns 16 columns (number of values between 1 to 10 with spacing of 0.4)  to the (2nd) row of (A). therefore A(1,2)=1.4 and A(1,3)=1.8 etc

Check the menus.

Check buttons.

Which version of Matlab do you use?

Open the help system.

Is the symbolic toolbox installed? What is the symbolic toolbox good for?

Use Matlab to calculate 3 + 4 * 5 and (3 + 4) *5.