12.07.2015 Views

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

do very fast operations on the appropriate matrices. matlab’s suite <strong>of</strong>utility matrices can also come in h<strong>and</strong>y when vectorising code (see helpelmat).We now look at a slightly more complicated example. Suppose youwant to generate a matrix a ij with elements:⎧⎪⎨a ij =⎪⎩j∑kk=ij ≥ i0 otherwiseThe 5 × 5 version <strong>of</strong> a is⎛1 1+2 1+2+3 1+2+3+4 1+2+3+4+50 2 2+3 2+3+4 2+3+4+5a =⎜ 0 0 3 3+4 3+4+5⎝ 0 0 0 4 4+50 0 0 0 5⎛1 3 6 10 150 2 5 9 14=⎜ 0 0 3 7 12⎝ 0 0 0 4 90 0 0 0 5⎞⎟⎠⎞⎟⎠A simple loop implementation <strong>of</strong> this calculation would resemble thefollowing:N = 200;a = zeros(N,N);for i = 1:Nfor j = 1:Nif j>=ia(i,j) = sum(i:j);endendendLet us time this code (call it forloop2):>>t0 = clock;forloop2;etime(clock,t0)ans =2.9241There are may different ways that we could vectorise this calculation,depending on our ingenuity. For now, we note that we can generate thec○ 2000 by CRC Press LLC

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

Saved successfully!

Ooh no, something went wrong!