Docsity

Numerical Methods Lecture Notes by L. Olson (UIUC) CS 257 - Prof. Luke Olson, Study notes of Computer Science

Partial preview of the text

Download Numerical Methods Lecture Notes by L. Olson (UIUC) CS 257 - Prof. Luke Olson and more Study notes Computer Science in PDF only on Docsity!

Lecture 3

Numerical Methods

L. Olson

Department of Computer Science University of Illinois at Urbana-Champaign

On a sheet of paper...

Name 1 or 2 "tricks" that you found helpful...

Luke’s: (^1) » [ rand(3) zeros(3,1) ] (^2) » figure;

Today: Programming Basics

Three things to keep in mind about Matlab when programming: (^1) everything is linear (^2) script versus function (^3) vectorize vectorize vectorize

Interpreter vs. Scripts vs. Function

Functions

save in functionname.m can have 0, n, or variable number of inputs can have 0, n, or variable number of outputs use return; to leave a function early use inline(...) to define without another file variables not "passed in" are local: only available within the function scope use global varname; to declare a variable that is visible through all functions

More on functions:

use eval to call a function from a string varnargin: variable number of argument inputs nargin: number of argument inputs varnargout: variable number of argument outputs nargout: number of argument outputs

Vectorize!

The single most effective aspect in Matlab in order to build efficient code:

function test1(n) t=cputime; for j=1:n x(j) = sin(j); end disp(cputime-t);

function test2(n) t=cputime; j=1:n; x=sin(j); disp(cputime-t);

test1(10000)

test1(100000)

test2(100000)

test2(1000000)

More vectorization: Memory

Preallocate memory: set size of the matrix beforehand: A=zeros(n) this allocates a chunk of memory at ones instead of multiple times on the fly

function test3(n)

t=cputime; for j=1:n x(j) = sin(j); end disp(cputime-t);

function test4(n)

t=cputime; x=zeros(1,n); for j=1:n x(j) = sin(j); end disp(cputime-t);

test3(100000)

test4(100000)

Visualizing Data

» A=rand(10); » surf(A);

» A=diag(ones(100,1)) + diag(ones(40,1),60); » spy(A);

Advice on programming

use disp pause spy surf whos profile and semicolons to help debug and visualize your code. Matlab’s in-house debugger often not enough vectorize when you can avoid loops when you can modularize your code...this will take practice

An excercise...

newspy(A)

plots red for negative values in the matrix plots blue for positive values in the matrix plots green for zeros values in the matrix

An excercise...

newspy(A)

plots red for negative values in the matrix plots blue for positive values in the matrix plots green for zeros values in the matrix

read §3.4 - §3. glance at chapter 4 start playing around with the wiki