


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Effective programming
Next example shows three different ways of computing an inner product of two vectors.
zi = xi · yi, i = 1, 2 ,... , n
Method 1: Do not allocate memory space for z in advance. Compute the elements in the new vector by a for-loop.
x = rand(n,1); % random vector y = rand(n,1); % of length n clear z; t = cputime; for i=1:n z(i) = x(i)*y(i); end cputime-t
Method 2: Allocate space for z in advance, but still use a for loop. z = zeros(n,1); for i=1:n z(i) = x(i)*y(i); end
Method 3: Use vector operation in Matlab directly.
z = x.*y;
Result (The CPU-tie measured in seconds):
n Method 1 Method 2 Method 3 5000 2. 86 0. 24 0. 00 10000 14. 22 0. 49 0. 00 20000 59. 65 0. 97 0. 01 100000 −− 4. 87 0. 03 1000000 −− 48. 84 0. 30
Matlab’s adaptive Simpsons metode: quad
Syntax:
q = quad(’f’,a,b,toleranse,trace)
If trace 6 = 0, Matlab will show the development of the integration.
quad(’f3’,0,2*pi,1.e-6,1)
Matlab’s recursive numerical integration: quadl and quad
Syntax and usage would be the same as for quad. The functions use a high order recursive algorithm.
quadl is prefered over quad8.