03.03.2014 Views

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

16 CHAPTER 2. A “CRASH” COURSE IN OCTAVE/MATLAB<br />

• eig(M) returns the eigenvalues of M. [V, LAMBDA] = eig(M) returns the eigenvectors, and<br />

eigenvalues of M.<br />

2.3 Programming and Control<br />

If you are going to do any serious programming in octave, you should keep your commands in a<br />

file. octave loads commands from ‘.m’ files. 2 If you have the following in a file called myfunc.m:<br />

function [y1,y2] = myfunc(x1,x2)<br />

% comments start with a ‘%’<br />

% this function is useless, except as an example of functions.<br />

% input:<br />

% x1 a number<br />

% x2 another number<br />

% output:<br />

% y1 some output<br />

% y2 some output<br />

y1 = cos(x1) .* sin(x2);<br />

y2 = norm(y1);<br />

then you can call this function from octave, as follows:<br />

octave:1> myfunc(2,3)<br />

ans = -0.058727<br />

octave:2> [a,b] = myfunc(2,3)<br />

a = -0.058727<br />

b = 0.058727<br />

octave:3> [a,b] = myfunc([1 2 3 4],[1 2 3 4])<br />

a =<br />

0.45465 -0.37840 -<strong>0.1</strong>3971 0.49468<br />

b = 0.78366<br />

Note this silly function will throw an error if x1 and x2 are not of the same size.<br />

It is recommended that you write your functions so that they can take scalar and vector input<br />

where appropriate. For example, the octave builtin sine function can take a scalar and output a<br />

scalar, or take a vector and output a vector which is, elementwise, the sine of the input. It is not<br />

too difficult to write functions this way, it often only requires judicious use of .* multiplies instead<br />

of * multiplies. For example, if the file myfunc.m were changed to read<br />

y1 = cos(x1) * sin(x2);<br />

it could easily crash if x1 and x2 were vectors of the same size because matrix multiplication is not<br />

defined for an n × 1 matrix times another n × 1 matrix.<br />

An .m file does not have to contain a function, it can merely contain some octave commands.<br />

For example, putting the following into runner.m:<br />

2 The ‘m’ stands for ‘octave.’

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!