SUNY Geneseo Department of Mathematics
Friday, November 6
Math 230 01
Fall 2015
Prof. Doug Baldwin
derivative
to create an anonymous
function from f and return that anonymous functionfunction fprime = derivative( f )
%DERIVATIVE numerically differentiates a given function.
% Works by creating a function that takes an x value at which to calculate
% the derivative, and that calculates a symmetric difference quotient of
% the original function around that x value.
tolerance = 1e-10;
fprime = @(x)( f( x + tolerance ) - f( x - tolerance ) ) / ( 2 * tolerance );
end
>> f = @(x) x^2
f =
@(x)x^2
>> fprime = derivative( f )
fprime =
@(x)(f(x+tolerance)-f(x-tolerance))/(2*tolerance)
>> fprime( 3 )
ans =
6.0000
>> fprime( -3 )
ans =
-6.0000
>> fprime( 1.4 )
ans =
2.8000
>> sinPrime = derivative( @sin )
sinPrime =
@(x)(f(x+tolerance)-f(x-tolerance))/(2*tolerance)
>> sinPrime( 0 )
ans =
1
for
loop repeats fixed number of timesfor var = first : last
body
end
for
iterates through a vectorfor var = vector
body
end
while
but while
repeats until
condition (doesn’t) holdtic
starts timer, toc
stops timer>> fprintf( 'hello world\n' );
hello world
>> %% print 'hello world' 100 times
>> for i = 1 : 100
>> fprintf( 'hello world\n' );
>> end
hello world
hello world
…
hello world
>> %% Sum integers from 1 to 100
>> % Expected result:
>> 1000 * 1001 / 2
ans =
500500
>> % With "for"
>> total = 0;
>> for i = 1 : 1000
>> total = total + i;
>> end
>> total
total =
500500
>> %% Sum without loop
>> sum( 1 : 1000 )
ans =
500500
>> %% Add all the numbers in vector v
>> v = rand( 1, 10 )
>> total = 0;
>> for i = v
>> total = total + i;
>> end
>> fprintf( 'Computed sum = %f, actual = %f\n', total, sum(v) );
v =
Columns 1 through 6
0.8147 0.9058 0.1270 0.9134 0.6324 0.0975
Columns 7 through 10
0.2785 0.5469 0.9575 0.9649
Computed sum = 6.238553, actual = 6.238553
>> %% Add all the numbers in vector v with indexing
>> v = rand( 1, 10 )
>> total = 0;
>> for i = 1 : 10
>> total = total + v(i);
>> end
>> fprintf( 'Computed sum = %f, actual = %f\n', total, sum(v) );
v =
Columns 1 through 6
0.1576 0.9706 0.9572 0.4854 0.8003 0.1419
Columns 7 through 10
0.4218 0.9157 0.7922 0.9595
Computed sum = 6.602112, actual = 6.602112
>> %% Add all elements of a matrix
>> m = rand( 4, 2 )
>> [ rows columns ] = size( m );
>> total = 0;
>> for r = 1 : rows
>> for c = 1 : columns
>> total = total + m(r,c);
>> end
>> end
>> fprintf( 'Computed sum = %f, actual = %f\n', total, sum(sum(m)) );
m =
0.6557 0.6787
0.0357 0.7577
0.8491 0.7431
0.9340 0.3922
Computed sum = 5.046410, actual = 5.046410