Download presentation
Presentation is loading. Please wait.
1
MATLAB 程式設計 Learning Loops and Logic
方煒 台大生機系
2
Ex9_1 Summing a series with a for loop
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)
3
Ex9_2 Products with a for loop
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)
4
Ex9_3 Recursion relations with for loops
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
5
Ex9_4 Logic 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 c=a*b % otherwise multiply them to obtain c
6
Ex9_5 Secant method % set chk, the error, to 1 so it won’t trigger
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 x1=0.6 x1=0.6; % find f(x1) f1=func(x1); % find a nearby second guess x2=0.99*x1; % set chk, the error, to 1 so it won’t trigger % the while before the loop starts chk=1; % start the loop while chk>1e-8 % find f(x2) f2=func(x2); % find the new x from the straight line approximation and print it xnew = x2 - f2*(x2-x1)/(f2-f1) % find chk the error by seeing how closely f(x)=0 is approximated chk=abs(f2); % load the old x2 and f2 into x1 and f1; then put the new x into x2 x1=x2;f1=f2;x2=xnew; end
7
Ex9_6 Using fzero 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 sign is used to tell Matlab that % the name of an M-file is being passed into fzero %***************************************
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.