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.

To get the following result Iused trial <strong>and</strong> error to get the right valuesfor the surface reflectance properties:clfh = surf(x,y,z);set(h,’facecolor’,[.5 .5 .5],...’edgecol’,’none’)hl = light(’pos’,[1000,0,0]);axis equalaxis <strong>of</strong>fview(-20,0)set(h,’specularstrength’,0)set(h,’ambientstrength’,1)set(h,’diffusestrength’,10)set(h,’backfacelighting’,’unlit’)38 <strong>MATLAB</strong> Programming38.1 Vectorising CodeIonce heard Cleve Moler say, “The for loop gets a bad rap.” One<strong>of</strong> the clearest ways to see the truth <strong>of</strong> this statement will be in thissection on speeding up matlab routines by vectorising code. We will beeliminating for loops <strong>and</strong> replacing them with operations on vectors ormatrices. Yet, do not think that you must then eliminate all for loopsfrom your matlab code. When for loops are used appropriately theyare still very fast, efficient, <strong>and</strong> convenient. With this proviso, let uslook at an example.matlab’s diff function takes the difference between successive pairs<strong>of</strong> elements in a vector, <strong>and</strong> writes them to another vector. Suppose youwant to carry out a similar operation, except now you want to computethe sum <strong>of</strong> successive pairs instead <strong>of</strong> the difference. In mathematicalnotation, you would write the formula:b i = a i + a i+1 , i =1, 2,...N − 1.where a is the input vector <strong>of</strong> length N, <strong>and</strong> b is the output vector <strong>of</strong>pairwise sums. The following piece <strong>of</strong> matlab code would do the job:N = length(a);b = zeros(1,N - 1);for i = 1:N-1b(i) = a(i) + a(i + 1);endThis code, or at least the line inside the for loop, has the advantage<strong>of</strong> resembling the mathematical notation quite closely. We measure thec○ 2000 by CRC Press LLC

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

Saved successfully!

Ooh no, something went wrong!