MATLAB Learning Loops and Logic MATLAB Ex 91
MATLAB 程式設計 Learning Loops and Logic 方煒 台大生機系
MATLAB 程式設計 Ex 9_1 Summing a series with a for loop n n n s=0; % set a variable to 0 so that 1/n^2 can be repeatedly added to it N=10000; % set the upper limit of the sum for n=1: N % start of the loop % add 1/n^2 to s each time, then put the answer back into s s=s+1/n^2; end % end of the loop fprintf(’ Sum = %g n’, s) % print the answer % calculate the sum of the squares of the reciprocals of the % integers from 1 to 10, 000 n=1: 10000; sum(1. /n. ^2)
MATLAB 程式設計 Ex 9_2 Products with a for loop n n n n P=1; % set the first term in the product N=20; % set the upper limit of the product for n=2: N % start the loop at n=2 because we already loaded n=1 P=P*n; % multiply by n each time and put the answer back into P end fprintf(’ N! = %g n’, P) % print the answer factorial(20) gamma(21)
MATLAB 程式設計 Ex 9_3 Recursion relations with for loops n n n a(1)=1; % put the first element into the array N=19; % the first one is loaded, so let’s load 19 more for n=1: N % start the loop a(n+1)=(2*n-1)/(2*n+1)*a(n); % the recursion relation end disp(a) % display the resulting array of values
MATLAB 程式設計 Ex 9_4 Logic n n n n clear; a=1; b=3; % If the number a is positive set c to 1; if a is 0 or negative set c to 0 if a>0 c=1 else c=0 end % if either a or b is non-negative, add them to obtain c; % otherwise multiply a and b to obtain c if a>=0 | b>=0 % either non-negative c=a+b else c=a*b % otherwise multiply them to obtain c end
MATLAB 程式設計 Ex 9_5 Secant method n n n n n clear; close all; %****************** % Define the function as an in line function %****************** func=inline(’exp(-x)-x’, ’x’); % First plot the function x=0: . 01: 2; f=func(x); plot(x, f, ’r-’, x, 0*x, ’b-’) %****************** % From the plot the solution is near x=. 6 % Secant method to solve the exp(-x)-x = 0 % Use an initial guess of x 1=0. 6 %****************** x 1=0. 6; % find f(x 1) f 1=func(x 1); % find a nearby second guess x 2=0. 99*x 1; n n n n % set chk, the error, to 1 so it won’t trigger % the while before the loop starts chk=1; % start the loop while chk>1 e-8 % find f(x 2) f 2=func(x 2); % find the new x from the straight line approximation and print it xnew = x 2 - f 2*(x 2 -x 1)/(f 2 -f 1) % find chk the error by seeing how closely f(x)=0 is approximated chk=abs(f 2); % load the old x 2 and f 2 into x 1 and f 1; then put the new x into x 2 x 1=x 2; f 1=f 2; x 2=xnew; end
MATLAB 程式設計 Ex 9_6 Using fzero n n n n n function f=fz(x) % evaluate the function fz(x) whose % roots are being sought f=exp(-x)-x; %******************** % Here is the matlab code that uses fz. m to find % a zero of f(x)=0 near the guess x=. 7 % Note that the @ sign is used to tell Matlab that % the name of an M-file is being passed into fzero %******************** x=fzero(@fz, . 7)
- Slides: 7