Intro to Programming in MATLAB


program =

Elements of a programming language


Algorithms and pseudo-code

Problem description: Recall the bug-hopping problem from Team Lab. Write a MATLAB program that asks the user for the length of the bar and then solves the bug-hopping problem for a bar of that length.

  Tk =

  Tk =

Algorithm (high-level):
  1. Get # of points on bar from user
  2. Create coefficient matrix A
  3. Create RHS vector b
  4. Solve linear system Ax = b
  5. Display results
             Rewrite in pseudo-code
= english-like description that uses the language of programming

    for example,

Each line of pseudo-code should correspond to just a few lines of MATLAB code

Algorithm (pseudo-code):

  1.  
  2.  

     

     

     

     

  3.  

     

     

  4.  
  5.  

     


User input

var = input( prompt )

Read in a scalar:

Command Window:

Read in a vector/matrix:
— user must enter vector/matrix

Command Window:

 

Read in a string:

Option 1: user enters the quotes

Command Window:

Option 2: indicate in input command

Command Window:

 

 


Basic for loop

for counter = first : increment : last
    statements % body of loop
end

Example: what does data contain after the following code is run?

data = 1 : 12;
for k = 1 : 3 : 12
    data(k) = data(k) + 10;
end

 

 

Example: roll a 6-sided die 1000 times and report the value on top

 

 

 

 

 

randperm(N)