Sei sulla pagina 1di 6

Introduction to Matlab programming

Semester 2, 20122013
You should check the Matlab help every time you nd a new command you don't know. Some exercises have hints including useful operations, use them! Some useful commands that you should use at the beginning of most of your scripts for sanity reasons: clear all, close all, clc.

Part I  Basic exercises: variables, vectors and matrices


Exercise 1 (

Obj X

use slr opertorsD deE (ne vrileD use prede(ned onstntsF Hints X D piD sqrt

very easy )

a. Dene a variable named area with the area of a circle of radius 5 b. Dene a variable side with the side length of a square of area 10 c. Dene a variable sur with the surface area of a cylinder of height 2 and radius 5 Given the following arrays x=[0 2 3]', y=[2 -3 4], A=[0 8;-4 3;-2 5] and B=[9 7 6;8 5 -1], determine for each command whether it can execute correctly; in the case it doesn't explain why; in the case it does, predict the size of the result. Check your answer with Matlab. a. x+y b. x+y' c. x*y d. y*x e. A*y f. A'*x g. B'*A h. y*A*B*x

Exercise 2 (

Obj X

rete nd operte with vetor nd mtries Hints X trnspose 'D new row [;]

very easy )

Exercise 3 (

Obj X rete vetorsD plot Hints X plot, lineSpec

very easy )

Plot the function sin(x), x [0, 2]

Exercise 4 (

Obj X vetorsD plot Hints X

very easy ) normal )

Plot the function y = 2x + 5, x [0, 10]

Exercise 5 (

Obj X vetorsD dot opsF Hints X .*D ./

Do it! this is the important one. Plot the function y = x2 2x + 5, x [0, 5]

Part II  Introduction to ow control and scripts


Good programmers comment their code to explain what they're doing. They start each line of comments with the % symbol, which makes sure the computer doesn't read those lines.

It is recommended to solve each exercise in a separate matlab le. For example, Ex01.m, Ex02.m, Ex03.m, ... Naming rules
There are some rules you have to follow when naming a matlab le:

    

names cannot have spaces names cannot include symbols (forbidden symbols include %, -, +, *, /, &, $, ...) names cannot start with numbers you cannot use the same name for a le and a variable it is not a good idea to have a le (or a variable) with the same name as a matlab function (for example max, min, sum, i, pi, exp, cos, ...)

 it is not a good idea to use folder names including spaces


Loops  Basic syntax of if and for instructions

if condition % code to run if condition is true else % code to run if condition is false end for I = start:stop % code to run each iteration end
Loops  Example 1: going along a vector

% loop on elements of vec for I = 1:length(vec) % display the squares of the coefficient of vec disp( vec(I)^2 ); end
Note that this loop works for

any vector, doesn't matter its size.

Loops  Example 2: accumulation

% initialize accumulator acc = 0; % loop on elements of vec for I = 1:length(vec) acc = acc + vec(I); end % display result disp(acc)

Loops  Example 3: while loops

% initialise I = 0; % loop while I < 10 % display disp(I) % increment I I = I + 1; end


While loops are very useful when you don't know in advance how many cycles you want. Try to understand how following example works

% the vector r has 100 random numbers between 0 and 1 r = rand(100,1); I = 1; while r(I) <= 0.9 I = I + 1; end disp(I)

Part III  Flow control exercises


Obj X if sttements Hints X ifDelse
Exercise 6 (

easy )

Implement a matlab script with three variables a, b, and c that sorts these three values in ascending order by comparing and exchanging their values. At the end of the program a <= b <= c must hold. You can solve this exercises with three if in minimum. Test your method with all six permutation of three dierent numbers. Given v=[0 -2 3 8 5 2 -5 -2], and m=4, write a script that displays the number of coecients of v smaller than m. Modify v and m and try it again to be sure that your program works with any vector. Write a script that outputs a right isosceles triangle of height and width n, so n = 6 would look like

Obj X loopD ifD umulte Hints X length

Exercise 7 (

easy )

Exercise 8 (

Obj X for loops Hints X

normal )

* ** *** **** ***** ****** Use for loops. Try it for dierent values of n

Part IV  Functions
Basic syntax

function result = functionName(inputParam1, inputParam2) % % this is a functions that receives two input parameters and % returns one value (the value stored in the result variable) % % Note: it is a horrible practice to use the instruction "input" % inside a function % function code goes here - this code will use inputParam1 and % inputParam2 to compute the value of result % you have to set the variable result to some value that % will be returned result = ...
One key detail of functions is that the variables inside the functions are . That means that no one but the code of the function can see or modify the value of any variable dened within the function. In the same way the code of the function cannot use variables dened in other .m les. All the values needed by a function must be provided as input parameters. All the results generated by a function must be returned as output parameters.

local

Part V  Function exercises


Obj X funtionsDloop Hints X
Exercise 9 (

normal )

Create a function called mystats that receives a vector and returns the sum of all coecients, the max and the min of the vector. To return multiple values dene your function as

function [theSum,theMax,theMin] = mystats(vec)


You can call the function using the same format. The number can be estimated as

Obj X funtionD loopD plot Hints X pi

Exercise 10 (

normal )

2 8 = 16

1 (2n + 1)2 (2n 1)2

n=1

a. Create a functions p = calcPi(n) that estimates using the rst n terms of the series. b. Write another function, n = nTerms(tol), that returns how many terms are required to get an error smaller than tol.

Obj X funtionsDloop Hints X


Exercise 12 (
to evlute pF

Exercise 11 (

normal )

Create a function, evaluatePolynomial, that gets a vector with the coecients of a polynomial and a number x, and returns the evaluation of the polynomial in x. For example evaluatePolynomial([2 0 3 1],0.5) computes as follows: it returns the number: 2(0.5)3 + 0(0.5)2 + 3(0.5) + 1 Create a function plotPolynomial(p,xmin,xmax,n) that receives a vector p with the coecients of a polynomial, and plot it between xmin and xmax using n points. Do not copy the previous code! Call the function!

Obj X funtions Hints X se previous

easy )

funtion

Part VI  Advanced exercises (optional)


Obj X funtionD loopD plot Hints X Obj X funtionD loop Hints X F
Exercise 14 ( Exercise 13 (

normal )

Write a function that gets a number n and returns a vector p containing all the prime numbers smaller than n.  Create a script le to plot n vs the length of p Write a function that gets a number n and returns a vector p containing all the Mersenne primes smaller than n. When n = 2k 1 is prime it is said to be a

normal )

Mersenne prime

Obj X funtionD loop Hints X diff,find,isprime

Exercise 15 (

hard )

Write a function that gets a number n and returns a prime gap of size n. A prime gap is the dierence between two successive prime numbers. Example (14, 15, 16) is a prime gap of size 3. The rst prime gap of size 21 is (1130 1150)  Could you make a vectorised version of the previous function? Write a function that gets a number n and returns all the numbers smaller than n that can be written as the sum of two cubes in two dierent ways. For example 13 + 123 = 93 + 103 = 1729. Other examples are (9, 15) and (2, 16) (15, 33) and (2, 34) (16, 33) and (9, 34) (19, 24) and (10, 27)

Obj X loop Hints X

Exercise 16 (

hard )

Obj X loop Hints X

Exercise 17 (

hard )

Generate a matrix with all binary codes from 1 to n

Obj X loop Hints X

Exercise 18 (

very hard ) very hard ) insane )

Create a function which gets a string N with a roman numeral and returns its decimal value. symbol value I 1 V 5 X 10 L 50 C 100 D 500 M 1000

Obj X loop Hints X rem Obj X loop Hints X

Exercise 19 (

Write a function that gets a number n and returns all numbers smaller than n that are divisible by all its digits.

Exercise 20 (

Create a function which gets a number n and returns the roman numeral

Potrebbero piacerti anche