38
Lecture 1 Getting Matlab to run On your own laptop...you're on your own... On Athena type (without the athena% prompt) athena% add matlab athena% matlab It takes about 30-60 secs to start up... and you'll get a screen showing: < M A T L A B > Copyright 1984-2006 The MathWorks, Inc. Version 7.2.0.283 (R2006a) January 27, 2006 To get started, type one of these: helpwin, helpdesk, demo, help help, whatsnew, info For Athena-specific information, type: help athena For product information, visit www.mathworks.com To start the Matlab Desktop, type: desktop >> desktop Alternatively, you can type athena% add matlab athena% matlab -desktop Programming

Matlab Lectures

Embed Size (px)

Citation preview

Page 1: Matlab Lectures

 Lecture 1

Getting Matlab to run

On your own laptop...you're on your own...On Athena type (without the athena% prompt)

athena% add matlabathena% matlab

It takes about 30-60 secs to start up... and you'll get a screenshowing:

                             < M A T L A B >                  Copyright 1984-2006 The MathWorks, Inc.                         Version 7.2.0.283 (R2006a)                              January 27, 2006

   To get started, type one of these: helpwin, helpdesk, demo,  help help, whatsnew, info  For Athena-specific information, type: help athena  For product information, visit www.mathworks.com   To start the Matlab Desktop, type: desktop >> desktop

Alternatively, you can type

athena% add matlabathena% matlab -desktop

Programming

The most awful truth about computers is that they are all dumb. Everything must be explicitly told. Spelling out the most minor and obvious detail. Otherwise, you will either get a syntax error (computer not understanding what you are saying) or a programming error (the computer understanding what you are saying but it is different from what you mean). There are many programing languages. Why use Matlab? As a first programming language, it is great, it has simple syntax, it is easy to get started with and easy to do graphics. While other

Page 2: Matlab Lectures

programming languages are faster running they are slower to learn and to use.In addition, Matlab, as an interpreted language, is interactive, which allows for more exploratory programming. Once the exploration is done, one should consider rewriting the program in a different language if intensive use is required.

The Command Prompt

In the interactive terminal of Matlab you will see the command prompt (>>). This is Matlab's way of telling you that it is ready to receive instructions from you. To command Matlab, type your request and hit Enter. Matlab then evaluates your command and displays the output (if any).

To get help use the help, and lookfor commands. help should be used to find out information about a known command, e.g. help zeros. lookfor can be used to find a command to perform a task e.g. lookfor roots.If you do not get the command prompt for some reason, you may have typed a syntax error, or have put Matlab into an infinite loop. Don't panic! press Ctrl-C and you'll get the prompt back.

 Exercises

Learn about the commands ones, zeros, sum, and diag. Learn about magic and verify what you learned with sum.

Simple Expressions

Matlab's most basic building blocks are expressions: 1, 1+1,4*3, 4^2, 5/6. But Matlab's real strength is in handling matrices and vectors. To enter a vector we use brackets. Try the following examples to see what happens: [1 2], [1:10], [1, 2 3 4; 5 6, 7 8 ; 9 10 11 12]Notice that the colon is used to create an arithmetic sequence. We can also create a sequence with a step-size different from 1: [4:0.1:5], [5:-2:-5].To transpose a matrix (or vector) use the apostrophe ('):

>> [1:10]'

Exercises

Try to solve these with a single Matlab command:

Create the vector consisting of the whole even numbers between 15 and 27.

Page 3: Matlab Lectures

Create the vector consisting of the whole odd numbers between 15 and 27. Create the vector of the previous question in decreasing order.

Variables

Asking Matlab to calculate things for us is great, but most of the times a calculation is only one step out of many and the result of a calculation need to be saved for the (very near) future. To do this we use 'variables', which are simply a way to name a bit of Matlab data. This is best explained by example:

>> a=1

puts the value 1 into a variable called a. typing

>> a

results back in the value 1.

We can also assign a calculation into a variable:

>> b=1+1

and now b will contain the answer, 2.

Variable names can (and should) be longer than one letter. A word or a couple of words strung together tends to work the best.

Referencing matrix elements

We can access the elements of a matrix in the following manner:

>> a=[1 4 3 5 6]>> a(4)

>> b=[1 2 ; 3 4]>> b(2,2)

Where the numbers in the parenthesis are (row, column). 

Page 4: Matlab Lectures

Lecture 2

Accessing Matrix Elements

Submatrices

We already say in the previous lecture that you can access the (2,3)th element of a matrix a with the notation

>> a(2,3)

This gives the entry of a in the second row and the third column.

We can  also gain access to several elements at the same time. Try for example:

>> a(2, [1 2])>> a([3 4], 3)>> a([2 3], [3 4])

These commands extract a submatrix of a with the corresponding set of rows and columns.

It is often useful to extract a whole row or column of a given matrix. Assuming that B has 10 rows, we can extract the second column of B with the command

>> B(2,1:10)

Using the column notation instead of spelling out [1 2 3 4 5 6 7 8 9 10].In fact, there is more shorthand to be learned here. First, we can replace the 10 with the keywordend:

>> B(2,1:end)

This keyword gets replaced by the largest number allowed for that place. So if it is used in the rows it will be replaced wit the number of rows, if in the columns, with the number of columns. It is useful to know that one can manipulate it as one would any other variable:

>> B(2,1:end-1)>> B(2,1:end/2)

Page 5: Matlab Lectures

Of course, if by the manipulation you get an illegal expression, matlab will complain:

>> B(2,1:end+1)>> B(2,sin(end):end)

The 1:end construction is so useful that Matlab has a further shorthand for it:

>> B(2,:)

Means the same as  B(2,1:end). So, one should think of the bare colon (:) as meaning "everything".

Non-contiguous element access

The elements of the matrix that we access do not have to be contiguous:

>> a(3,[2 4 6])>> a([2 4], [1 3])

They don't have to be in increasing order:

>> a(3,[2 6 4])>> a([4 1], [3 2])

Nor do they have to only appear once:

>> a(3,[2 2 4 4 1 1 1])>> a(3*ones(1,3),2*ones(1,10))

Exercises:

Verify that the sum along the anti-diagonal of the magic matrix is also the same as all the other rows, cols and the diagonal. (Hint: you can first change the order of the rows or columns before taking the diag)

 If A is a matrix, how can you get the sub-matrix of elements whose   both coordinates are odd?

Let x = [2 5 1 6] and y = [4 2 1 3]. Think of y as a specific reordering of the numbers 1:4. Use y to reorder x in the same fashion.

Page 6: Matlab Lectures

Given a ``permutation'' vector as y is in the previous item. Find the vector which gives the inverse of the permutation! (Tricky!)

Given two permutations p and q, find the permutations that is the same as p(q(s)) (that is it permutes the set s as if you would first permute with q and then with p)

Assigning into submatrices

Just as in the reference and assignment of single numbers into matrices, we can also assign new values into complete submatrices. The only thing that needs to be checked is that the matrix on the right of the equal sign has the same dimension as the matrix referenced on the left:

>> a([2 3],[1 4]) =[1 2 ;3 4]>> a(1,1:4)=2:5

Scalar expansion

Matlab has a nice time-saving notation. If an operator requires a matrix of a known size and instead is given a scalar (i.e a number). It "expands" the scalar into a full matrix of the required size. This is quite cumbersome to say...much better to show examples:

>>1:10.^2>>2.^1:10>>[1 2; 3 4] + 5

In these three cases, the relevant operator is looking for a matrix of the same size as the one it already has on the other side, but instead it finds a number. So Matlab pretends as if the matrix of the expected size is there with each of its entries equal to the number.

Exercises

Write an expression for the sum of the integers from 1 to 100 Write an expression for the sum of the squares of the numbers from 1 to 10 Write an expression for the sum of the powers of 0.5 to the numbers from 1 to 10 Let x = [2 5 1 6]. Add 3 to just the odd-index elements (resulting in a 2-

vector), adds 3 to them and puts the result in the even positions of the original

Page 7: Matlab Lectures

vector (overwriting the 2 and the 1).

Lecture 3

Matrix concatenations 

Using the brackets we can create more and more complicated matrixs:

>> [ones(2,2) zeros(2,2)]>> [ones(2,2) ; zeros(2,2)]

E x e r c i s e

Create the matrix whose first column is the numbers 1:10, the next column contains the first 10 squares 1, 4, 9 ...100 and the third column contains the first 10 powers of 2: 2 4 8 16...1024.

More Expressions

All Matlab expressions are made out of basic building blocks put together: 

Constants Variables Operators Keywords Functions

 

Constants

We have met some constants already: 1, 3, 1.56, -5, pi. But there are more that we haven't yet met: i, j, (root of -1), 2.4e12 (2.4 times 10^12), 'a' (the character a),'hello' (a vector consisting of the letters 'h','e','l','l','o').  Note that i and jcan be used in a way different from variables: you can write 3i or -15j, but if you define a=10, writing 4a is an error... Also note that Matlab allow using the colon notation with letters:'a':'z'. 

Page 8: Matlab Lectures

Note that you can access letters in a string just elements in any other vector:  >> a='hello'   >> a(2)>> a(4:5)='p!' 

E x e r c i s e :

Create the string of letters 'zyx....cba' Intertwine the two strings 'Hello!!' and 'Goodbye' (create the string

'HGeolold....!e')

Variables

There isn't much to say about variables. Variable names must start with a letter, and the variable name length must be no more than 32 characters. Names may use letters, numbers and the underscore '_'. Note that matlab will make matrixs and vectors grow as needed (filling the empty spaces with zeros): >> a = [1 2 ; 3 4]>> a(5,5) = 1 

Operators

We have met many operators: =,+,-,/,*,^,.,',[,],(,),;,:. There are a few others, as we shall see shortly.

Keywords

We have not yet seen many keywords...the only exception is end. 

Functions

We have seen: ones, zeros, diag, size,...There are others. For example: sin, cos, exp, log, sqrt. You can also define new functions as we shall learn in the next lecture or two. 

Plotting

Page 9: Matlab Lectures

Let's learn how to make nice pictures. plotting is one of the basic tools of Matlab. Most of the plotting happens through plot and its variants. Best is to learn by example: >> x = 0:0.01:1 ;>> y = sin(x) ;>> plot(x,y) Notice several things. First, the semicolon ';' at the end of the expression suppresses the output of the result. However, it does not inhibit the evaluation of the expression. So x and y are still as they would be if the semicolon was missing but the screen is blissfully clean (try it without the semicolon).Second, notice that the plot function created a nice figure for us, with the first "wave" of the sin. try it put with other functions. 

E x e r c i s e :

Plot the sin over a different interval Plot a more squiggily sin over the same interval plot the function x^2 between the numbers -5 and 5 plot the function log(x) from 1 to 10 (be sure that your plots

are nice and smooth) plot a circle (think parametric plot) plot a Lissajou curve Plot a "heart" r = sin(theta/2) Read more about plot and its optional arguments!

Note that using plot with only one input argument does something a little strange (but useful at times...). 

Logical Constructs

Sometimes it is important to compare numbers. For example we might want to act differently if a given number is positive or negative. For this we need logical operators and comparisons.  

Testing

Page 10: Matlab Lectures

First, comparisons. we use the operators ==, ~=, < >, <=, >=  (the ~ key is usually at the top left of the keyboard, and it needs the SHIFT key) to compare numbers e.g:

>> 1==2>> 3~=5>> 5<=6>> 7<=10

Notice that these expressions return 0 when they are false and 1 when the are true. This is the convention. 0 is false and 1 is true. While this notation looks similar to math, there are a few pitfalls

1<x<5 does NOT return what it does in math...in fact this will alway be true regardless of the value of x. Can you see why?

== is not =. Regardless of how many time I will say this, people will still make this mistake many times...but perhaps by saying it lots, it will happen less...maybe. remember...you have been warned...= is assignment, and == is a test for equality.

Boolean operations

What if we want to check two things? A and B? or perhaps A and (B or C)...for this we need Boolean operators: & (AND), | (OR), and ~(NOT)(The | is usually found at the middle right of the keyboard, and it needs a SHIFT key.)

1~=2 | 3<4 3~=4 & 8==(4+4) ~(2<=8) 

Formatting Text

Once in a while we would like to display some text that is nicely formatted and not just the output as Matlab wants to display. To do this we use the sprintf command.In its simplest form it is quite straightforward...the first arguemnt is a format string, and the rest are parameters for the string. examples:

sprintf('hello, here is a number %d',17)

Page 11: Matlab Lectures

sprintf('my name is %s and I am %g years old','Yossi',31)

Read up on sprintf to get the whole picture.  

 Lecture 4Warm up Exercise:

Evaluate the sum of -1^(n+1) / (2n-1) for n from 1 to N where N=100. Find a value of N so that the sum is close to pi/4 (with difference < 10^-6)

Flow Control

Up to now, we saw how to make Matlab execute a list of commands without any decision making. Now we will learn to have Matlab do different things depending on the results of previous expressions.

if Statement

We might want have Matlab evaluate a bunch of expressions if some condition is satisfied, and another bunch of expressions otherwise. The syntax for this is (don't type this into Matlab..)

if condition    Bunch    Of    expressionselse    Other    expressionsend

Note that you must replace the condition with an expression that Matlab will evaluate first. 

Example:

Page 12: Matlab Lectures

>> if 3<4    '3 is less than 4'else    '3 is not less than 4'end>>

Since the condition is true, the expression which is evaluated is '3 is less than 4', and this is then displayed on the screen.

We can try something more interesting. Type the following into a file (say, if_example.m)

x = rand;s = 'The number %g is %s than 0.5\n';if x<0.5    fprintf(s,x,'less')else    fprintf(s,x,'more')end

Save the file and run it (either from the menu, or by typing the name of the file). You might be asked to change directory, do that.As you know, rand returned a (pseudo-)random number (to initialize it, you need to call something like rand('twister', sum(100*clock)), but read more about rand to find out why.) fprintf is similar to sprintf except that it  writes the result instead of returning it. If you want to understand this a little further..read the help files and look at the difference in the output from the following commands: >> a=sprintf("Hello!") >> b=fprintf("Hello!") 

The '\n' at the end of the string s is to make sure that Matlab actually goes down a line before returning us the command prompt...try removing it and see what happens.

What is Truth?

Page 13: Matlab Lectures

I'm not trying to get all philosophical or anything, but we need to know what matlab considers to be "true" and what to be "false", if we want to understand how the execution of an if statement works. For this I want you to create another file (oracle.m) with the following 

if x     'True'else    'False'end

Then, from the command line, assign various values to x and run your file. See if each x value is true or false. Things you can try out. x=(1==4)x=4x=0x=[0 0]x=[]x=[0 1]x=[1 2 3] x='hello'x=''x=' 'x=-1x=i

for Loops

Loops are good when we want to do stuff over and over again. For example, if we didn't know how to sum up the elements of a vector using sum or linear algebra commands, we could use a loop to do it (a bad idea...much slower than the alternative, about 100 times slower!!! check out loop_timer.m if you care.) However, slow they may be, but we might still need them....The syntax is as follows:

for variable = vector    a bunch     of    expressions    here variable is an 

Page 14: Matlab Lectures

    ELEMENT of vectorend The way it works is that for every element in vector, matlab runs through all the commands in the block. during each such execution, the value of variable is set to that element...Let see a simple example:

for v = 1:10    v    v^2end Notice that  for every number from 1 to 10 we have two printouts (since there were two commands in the block) one simply the number and the other is the number squared...just as we asked. 

One can have any legal variable name instead of the variable, but note that it gets overwritten. Also the vector, can be any vector... for v = 'hello'    vend

One can "break out" of a loop before it is done by issuing a break command:

for v = 'hello and goodbye'    v    if v=='d'        break    end end

OK, enough new material..lets exercise!

Exercises

Find the sum of a vector x=[3 5 12 42 67] without using the old tricks...that is, use afor loop and don't use sum. 

Write a little program that checks if x=73 is prime. Do not use isprime. But you might find mod or rem useful.

Page 15: Matlab Lectures

Modify your program to find the first 20 primes  Write a program that find the error in the calculation from the top of the page

for N = 1, 10, 100,...10^6 and plots the results in a meaningful way. (you might want to consider using a log-plot, with loglog, or manually, taking the log from both axes before plotting)

 Lecture 5Warm up exercise

Write a for loop that calculates the first 20 Fibonacci numbers. Place result in a vectorFibo, so that Fibo(n) is the nth number. Recall that the sequence satisfies:

F(1)=1F(2)=1for n>2F(n)=F(n-1)+F(n-2)  

while Statements

Sometime, you need to iterate many times but don't really want to create a vector, or you don't know in advance how many time you need to iterate...for this you can use a while statement.

The syntax for a while statement is

while expression    a     bunch    of    statementsend

At the beginning of each iteration, Matlab evaluates the expression at the top of the loop. if it is true, Matlab executes the statements to the end. If it is false, Matlab jumps to the end and continues after it.

Page 16: Matlab Lectures

So, for example: >> x=10;>> while x>0x=x-1end>> will print out all the numbers from 9 to 0 (including both)   Take note of two things:  

Matlab does not check the expression all the time. Only before starting a new iteration

If the expression at the top is false when the first iteration should start, it will not. 

Exercises

Find the value of the 100th Fibonacci number, using a while loop, and no big vectors.

Write your prime checking program using a while loop instead of a for loop. Write a while loop that modifies n. if n is even it changes n to n/2, otherwise,

it changes it to 3n+1. if n is 1 the loop stops. Try this out for several different starting values. Count how many steps you need to get to 1.

 

Defining your own function

While Matlab has a vast collection of functions, sometimes you want to add some of your own. A function should be thought of as a black box, with a slot in the top (for the input) and a drawer at the bottom for the output. When you give the function input ("call the function"), it calculates the output and puts it in the drawer ("returns it"). Once the function is written, you do not need to care about how it works.  Functions must be defined in their own file, and the name of the file must match the name of the function. So, for example, to define a function called example_function_1, create a file named example_function_1.m. That file must start with the keyword function, so

Page 17: Matlab Lectures

 function y = example_function_1(x) is the first line of the file. let's dissect this first line:

functionAs I said, the first word must be "function".

y = This declares the local name of a variable whose value will be returned when the execution of the function is over.

example_function_1 The name of the function. This must match the name of the file.

(x) The local name of the variable that will contain the input value.

So the rest of the file could be  y=2*x;end admittedly, a very boring function: It takes the input value (locally called x), doubles it, and assigns that result to y. Since y is declared to be the return value and the function has ended, the return value is simply twice the input. we call the function by giving it a value: >> example_function_1(17) or >> example_function_1(rand) The return value can then be assigned to another variable: >> z= example_function_1(18);>> z  

Variable Scope

An important difference between a function and a script (the files that don't have "function" as their first word are called scripts) is that of "variable scope".

Page 18: Matlab Lectures

When executing a script from the command-line, the scripts has access to all the variables that are defined on the command line. For instance, if you have a script called script1.m whose contents are 

x+1y=y/2

and you run this script from the commandline like so:

>> x=2>> y = 6>> script1>> y 

You will see that the script knows that x=2 and that y=6. Not only this, note that y is changed in the scripts, the new value of y, 3 is also the value of y when check on the commandline. This seems natural, perhaps, but this is not how functions behave. A function with the same content function1.m

function function1x+1y=y/2

will fail to run, since within the function there are no such variables x and y. The variables of the function, are different from the variables outside the function, even if they have the same name. 

change your prime checking program so that the input is the number, and the output is 1 if the number is prime and 0 if not.

change your n-changing program, so that the input is the initial value of n and the output is the number of steps it took to reach 1.

use your primechecking function in another program (can be a script) that finds (a) the 1000th prime number and (b) the first prime number greater than 1000000.

use your n-changing function in another program (can be a script) that finds the number of iterations needed for the first 100 numbers, and plots then nicely. 

Page 19: Matlab Lectures

Lecture 6

Multiple Input Functions

 You can define a function to have more than one input. This is the syntax: function r = func1(x,y)  Remember that the name of the function must match the name of the file (with a .m added at the end). Therefore, no spaces, operators etc. in the name of the function. 

Exercise: 

 Make a function for which the input is x and y and the output is x^y. From the command line, check the following inputs:

o >powerfunc(2,3); powerfunc(3,2);o x=2; y=3; powerfunc(x,y); powerfunc(y,x)

You can define more than one function inside a function file: func2.m: function y = func2(x)y = helper(x) function r = helper(q)r = q^2;  In this way, the functions inside the file are visible to all the other functions in the file. However, only the first can be called from outside the file.  

More on Logic

Warm Up Exercises:

Page 20: Matlab Lectures

x = [1 5 2 8 9 0 1], y = [5 2 2 6 0 0 2].Evaluate and understand the following: 

o x>yo y>xo x==yo x<=yo x|yo x&yo x&~yo ((x>y)|(y>x))o x<5o x(y<5)

 x = [1:10], y = [3 1 5 6 8 2 9 4 7 0]. Evaluate and understand the following:

o (x>3)&(y<5)o x(x>5)o x(y>5)o y(x<=4)o x( (x<2) | (x>=8) )o y( (x<2) | (x>=8) )

(remember, all nonzero values are true)

Exercises: 

For x = [3 15 9 12 -1 0 -12 9 6 1]:o Set to 0 the positive elements of x.o Set to 3 the multiples of 3.

with 0 without 0

o Multiply by 5 the even elements of xo Create y from the elements of x that are > 10.o Set to 0 the elements less than the average.o Set to the distance from the average the elements greater than the

average.

 Create r and c such that:     ( 1 1 1 1 1 )     ( 2 2 2 2 2 )r =  ( 3 3 3 3 3 )     c = r'

Page 21: Matlab Lectures

     ( 4 4 4 4 4 )     ( 5 5 5 5 5 )

Using r and c, create ( 1 0 0 0 0 )          ( 1 0 1 0 1 )( 1 1 0 0 0 )          ( 0 1 0 1 0 )( 1 1 1 0 0 )   and         ( 1 0 1 0 1 )( 1 1 1 1 0 )          ( 0 1 0 1 0 )( 1 1 1 1 1 )          ( 1 0 1 0 1 )

Think about ideas for the final project. Ideas mentioned in class:

Chaoso Logistic equationo Mandelbrot Set

Combinatoricso 8 queens problem

Dynamicso Brownian Motion

Visual Illusiono Autostereogram

Interploationo Use a spline to recreate your name in cursive. 

Questions and Answers Question 1:   How to do questions 4 and 5?

Question 2:   What's wrong in my code about   mod ? Question 3:   What's wrong in my code about   sum ? Question 4:   What does the   %g   and   %s   represent? Question 5:   What's wrong in my code about finding a value of N so that the sum is close to pi/4?Question 6:   What would you suggest for my code about   while   loop? Question 7:   What's wrong in my code about matrix?

Question 1: I was working on the assignment and I see that I really have no idea how to do questions 4 and 5 in Lecture 2.Question 4: Given a ``permutation'' vector as y is in the previous item. Find the vector which gives the inverse of the permutation!Question 5: Given two permutations p and q, find the permutations that is the same as p(q(s)) (that is it permutes the set s as if you would first permute with q and then with p).

Answer 1: (HTML)

Page 22: Matlab Lectures

Question 2: I am having a little bit of trouble with the second exercise in Lecture 4: Write a little program that checks if x=73 is prime. Do not use isprime. But you might find mod or rem useful.

I came up with this: for x=[2 3 5 7 11 13 19] 

if mod(73,x)=0 'compound' else 'prime' end end

I thought this would work, but I get ??? Error: File: primenumbers.m Line: 2 Column: 17 

The expression to the left of the equals sign is not a valid target for an assignment.

I am not sure about what I am doing wrong. Could you please tell me? Answer 2: (HTML) Question 3: I can't get the warm-up exercise and hence the final exercise in

Lecture 4 to work properly. Warm-up Exercise: Evaluate the sum of -1^(n+1) / (2n-1) for n from 1 to N where N=100.Final Exercise: Find the sum of a vector x=[3 5 12 42 67] without using the old tricks...that is, use a for loop and don't use sum.

I haven't had a problem with sum before, but for some reason my syntax is calculating something other than the desired sum. I checked my matrix operators and I can't find anything wrong.  Here's my line: 

>> x= [1:2]  x = 1     2  >> sum((-1).^(n+1)/(2.*n-1))  ans = -0.0476 

But the answer should be .6667. Can you see what's wrong? Answer 3: The division needs to be pointwise. so use ./ instead of / . Question 4: I was running this if loop from your lecture notes in Lecture 4:

x = rand; s = 'The number %g is %s than 0.5\n'; if x<0.5 fprintf(s,x,'less') else fprintf(s,x,'more') end

Page 23: Matlab Lectures

Questions: What does the %g and %s represent? What does it say in english? Also are the alphabets random or each signify a different type of parameter?

Question: line 5 - fprintf (s,x, 'less') What does this say in english again? Why is s before x?

Answer 4: s is a "format string" when used as the first argument of fprintf or sprintf it tells the function how to generate the result (sprintf returns the result, while fprintf write the result to the screen, or a file).

In the format string, you can have "place holders" for other input. So the %g is a place holder for a number, and it will be converted to a string in the way that matlab shows numbers. %s is a placeholder for another string. The letters are not random...

So in the fprintf command, I'm saying, format the string s, using x as the first input (which will go where the %g is) and 'less' as the second input (which will go where the %s is).

Question 5: I have problems solving the second question in Warm-up Exercise in Lecture 4: Find a value of N so that the sum is close to pi/4 (with difference < 10^-6).

I have written the following code: counter=0; 

for n=1:10^(-6) a=(1).^(n+1)./(2.*n-1); sum(a); counter; if sun(a)-(pi/4)<10^(-6); break end end

and I had the following error message: ??? Error: File: lesson4ex6.m Line: 4 Column: 3 

Expression or statement is incomplete or incorrect. Answer 5: 

1. (line 2) 1:10^(-6) is an empty vector. Be careful with operator precedence.

2. (line 3) Even if that was a vector, it would only be a vector of size 10...and in the loop, n would just be a single number...not what you wanted I think. Perhaps you need another variable...just like my mathematics has two variables, N and n...they are not the same.

Page 24: Matlab Lectures

3. (line 6) Your "if" statement is incomplete. it must not have a newline after the if.

4. (line 7) sun is not sum. Beware of spelling mistakes. 5. (line 7) Remember that a difference might be positive or negative...so just

checking sum - pi/4 < tolerance is not enough...you need to use absolute value (lookfor it).

6. (line 8) Even if you add the absolute value, I'm not sure why you are breaking at this point. Remember, I want you to add 1, 10, 100, 1000 terms of the series and find the error. how does breaking help you do that?

The result of the calculation should be a vector (lets call it E, for error), of length 7 so that E(i) contains the error resulting from adding up 10^(i-1) terms.

Question 6: I have problem with the exercise in Lecture 5: Write a while loop that modifies n. if n is even it changes n to n/2, otherwise, it changes it to 3n+1. if n is 1 the loop stops. Try this out for several different starting values. Count how many steps you need to get to 1.

I have attached my version here. I can't seem to get it to work. What would you suggest?

function y = counter(x) counter1=1; while x>1 counter1=counter1 + 1; if mod(x,2)==0 x=x/2; else x=3*x+1; end y = counter1-1 end end

The below program is functional, but I don't know how to turn it into a function.

n=5 counter=1 while n>1 counter=counter + 1 if mod(n,2)==0 n=n/2 else n=3*n+1 end 

Page 25: Matlab Lectures

end fprintf('the n is %g', counter-1)

Answer 6: 2 comments.  1. You have an empty line as the first line of the code. The very first line must

have the "function y = ...." code, or a comment (starting with %). No empty lines allowed before the keyword function...This might be your only problem. 

2. You can put the y=counter1-1 outside the while loop. No need to make this assignment every iteration..only after you are done.

Question 7: For the additional exercise in Lecture 6: Create r and c such that:

     ( 1 1 1 1 1 )     ( 2 2 2 2 2 )r =  ( 3 3 3 3 3 )     c = r'     ( 4 4 4 4 4 )     ( 5 5 5 5 5 )

I tried a couple ways to create the matrix as follows, but some works and some doesn't. Could you tell me what's wrong? The following three ways have worked.

> > x = [1:5; 1:5; 1:5; 1:5; 1:5 ] x = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 > > x = [ ones(1,5); ones(1,5)*2; ones(1,5)*3; ones(1,5)*4; ones(1,5)*5 ]' x = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 > > ones(5,1)*[1:5] ans = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 

Page 26: Matlab Lectures

1 2 3 4 5 1 2 3 4 5

However this doesn't work. Why?

>> > ones(5,1) : ones(5,1)*5 ans = 1 2 3 4 5

Also, could you tell me how I can use ( : ) which you suggested after the lecture for me to create the matrix easily ?

Answer 7: The third way you suggested is one way I was thinking about (note that you can change the 5 to a 100 and it will create a 100x100 matrix...)

But you can also do a=[1:5]' 

r=a(:,ones(1,5)) The fourth way you did has a colon between two vectors...I'm not sure what 

you expect that to do.

Answer 1

I can only say so much about permutations without giving the whole thing away. Permutations are a reordering of a list. The *reordering* is the permutation...*not* the list. Once we have a reordering, we can use it to reorder any list (of the correct length). For example, taking the list 1 2 3 4 5 to the list 3 2 1 4 5 is a permutation, but we could use the same permutation and apply it to "d e s v t" and get "s e d v t" (make sure you see why) and so on.

A "standard" way of *writing* a permutation, is by writing what it does to the sorted set 1 2 3 4 5 (for a permutation of 5 elements) thus 3 2 1 4 5 is considered "the permutation" (even though it is not..it is only what the permutation does to the list 1 2 3 4 5). So y =[ 3 2 1 4 5] is a vector (in Matlab) and I want you to use this vector to permute a second list (since that is what all permutations love doing the most!) specifically, permute x = [4 3 7 8 2] (and get 7 4 3 8 2) somehow. (In the actual question 4 I used other examples.)

In question 5 I'm taking about combining permutations. If I have two permutations p and q, I can think of the combined permutation "permute by q and then by p" and I call it pq. So pq(s) = p(q(s)) where s is the list that I'm permuting. The question asks that you find how to find in Matlab this pq permutation given that you have p and q (to try it out, 

Page 27: Matlab Lectures

use specific p and q, e.g p = [2 1 3], q = [1 3 2] , note that pq != qp (not equal) since pq = [3 1 2] and qp = [2 3 1] ) .

Finally, p^{-1} is the "inverse" of p, i.e. the permutation so that p^{-1} = [1 2 3 4 5] the "identity" permutation, which doesn't do anything to the original list. For example [3 1 2] ^{-1} = [2 3 1] (and vice versa!!) the question is how to find the inverse in Matlab. I must note that you should not look for any special function. You can do this homework using ONLY what we have learn. Furthermore, the answers are one-liners! Very short, very elegant solutions.

Answer 2

The error message is telling you that the "mod(73,x)" is not a good candidate for "assignment". This means that you are telling Matlab to assign a value to mod(73,x) (not a good idea...). This is because you used the operator "=" instead of "==" (I told you that you will make this mistake...it's OK, everybody does...) 

So change the = to == and it should work..almost.  Notice that for every number(in the vector of primes) you will print 

something out...either 'prime' or 'compound'. So for a compound number (say 10) your program will show compound (2) prime (3)

and then by checking the output you will realize that it is compound...But that's not good enough...What if the output has 1000 lines? Do you want to have to check all of them? NO. You want your program to have a simple output: once only, compound, or prime. (You can break, once you have found a divisor, and then check the value of x, if it is the last number, you have reached the end of the loop (so prime) otherwise, you broke out of the loop (so compound). 

One more thing: The way you wrote your program, it is very clear that you have 73 as the only objective of the program. Once you have it running properly, try to modify it so that it can work for a general input variable something like this: 

input = 73;  for x = [some vector that depends on input, but does not use knowledge 

of prime numbers, etc]    if mod(input,x)==0      ...    end 

Page 28: Matlab Lectures

  ...   ... end ...