Download Lecture Notes: Introduction to MATLAB Functions - Spring 2009 (Math/CS 375) - Prof. Richar and more Study notes Computer Science in PDF only on Docsity! Math/CS 375 Spring 2009 Lecture 1e Introduction to MATLAB: Functions Ref: Appendix B Function: maxentry(A) function y = maxentry(A) % MAXENTRY Largest absolute value of matrix entries. % For vectors, MAX(X) is the largest element in X. % For matrices, MAX(X) is a row vector containing the % maximum element from each column. y = max(max(abs(A))); >> A = [1,2;3,4]; >>maxentry(1:10) >> maxentry(A) ans = ans = 10 4 marks (cont.) >> x_sort= marks(x) x_sort = 39 61 73 79 92 [x_sort, x_mean]=marks(x) x_sort = 39 61 73 79 9 x_mean = 68.8000 >>[x_sort, x_mean, x_med,x_std] =marks(x) x_sort = 39 61 73 79 92 x_mean = 68.8000 x_med = 73 x_std = 20.0549 if nargout > 2, x_med = median(x); end if nargout > 3, x_std = std(x); end >> x = [61,79,92,73,39]; >>x = 61 79 92 73 39 Function: ExpSum (Approximation to Exp(x)) function [sum,err,n] = ExpSum(x,maxn) % ExpSum computes an approximation to e^x, accurate to % machine precision, using its Taylor series. ExpSum returns % the approximation, sum, the relative error in the approximation, % err, and the required number of terms, needed to compute it, n. sum = 1; term = 1; n = 1; while abs(term) > eps*abs(sum) & n <= maxn term = term*(x/n); sum = sum + term; n = n + 1; end err = abs((sum-exp(x))/exp(x)); ExpSum (cont.) >> [sum,err,n] ExpSum(10,100) sum = 2.2026e+004 err = 1.6516e-016 n = 47 >> >> [sum,err,n] = ExpSum(-10,100) sum = 4.5400e-005 err = 2.0283e-009 n = 59 >> Why the difference in error between the approximation at x = 10 and x = -10? Subfunctions function w9plot % w9plot plots the functon w9(x), a component of the % error for polynomial interpolation using 9 points. % Define interpolation points and plot points, (xp,yp) x = [-4:+4]; xp = linspace(-4,4,100)'; yp = w9(xp); % Plot w9(x) along with the data points. plot(xp,yp,'g-',x,x,'r+'); title('Error function w9(x)'); xlabel('x'); ylabel('w9(x)'); % Subfunction w9(x) function z = w9(x) z = (x+4).*(x+3).*(x+2).*(x+1).*(x+0).*(x-1).*(x-2)... .*(x-3).*(x-4); w0d)
Cont.
Error function w(x)
6000 -—- T 1 1 T T
4000
3000
2000
1000 +
-1000
-2000
-3000
-4000
-5000 1 1 1 nl 1
-4 -3 -2 -1 o 1
Varargout function varargout = moments(x) %MOMENTS Moments of a vector. % [m1,m2,...,mk] = MOMENTS(X) returns the first, % second, ..., k'th moments of the vector X, where % the j'th moment is SUM(X.^j)/LENGTH(X). for j = 1:nargout, varargout(j) = {sum(x.^j)/length(x)}; end >> m1 = moments(1:4) m1 = 2.5000 >> >> [m1,m2,m3] = moments(1:4) m1 = 2.5000 m2 = 7.5000 m3 = 25 >>