Docsity

Numerical Methods - Study Guide for Exam | CS 257, Study notes of Computer Science

Toggle sidebar
bg1
Sheet1
Page 1
file contents output notes
function plotn(n)
x = linspace(0,1,n);
y = x.^n;
plot(x,y,'b-s',...
'MarkerSize',15,'LineWidth',2,...
'MarkerEdgeColor','k','MarkerFaceColor','g');
xlabel('x');
ylabel('y');
title('plotme example');
function f0(x,y)
z = x + y;
disp(z)
function z = f0(x,y)
z = x + y;
function [out1,out2] = f2(x,y)
out1 = x + y;
out2 = x * y;
function [approx, exact, err] = approxpi(n);
% approximate pi using Archimidis Example
radius = 0.5;
exact = pi;
approx = perimeter(radius,n);
err = exact-approx;
theta = linspace(0,2*pi,n+1);
x = cos(theta);
y = sin(theta);
c = err*ones(size(x));
figure(n);
fill(x,y,c);
title([num2str(n) '-sided polygon']);
text(0,0,['error = ' num2str(err)]);
axis off;
theta0 = linspace(0,2*pi,100);
x = cos(theta0);
y = sin(theta0);
hold on;
plot(x,y,'r-','LineWidth',3);
% subfunction: only called withing approxpi()
function p = perimeter(radius,n)
p = n*2*radius*sin(pi/n);
pf2

Partial preview of the text

Download Numerical Methods - Study Guide for Exam | CS 257 and more Study notes Computer Science in PDF only on Docsity!

Sheet Page 1 file contents output notes function plotn(n) x = linspace(0,1,n); y = x.^n; plot(x,y,'b-s',... 'MarkerSize',15,'LineWidth',2,... 'MarkerEdgeColor','k','MarkerFaceColor','g'); xlabel('x'); ylabel('y'); title('plotme example'); function f0(x,y) z = x + y; disp(z) function z = f0(x,y) z = x + y; function [out1,out2] = f2(x,y) out1 = x + y; out2 = x * y; function [approx, exact, err] = approxpi(n); % approximate pi using Archimidis Example radius = 0.5; exact = pi; approx = perimeter(radius,n); err = exact-approx; theta = linspace(0,2pi,n+1); x = cos(theta); y = sin(theta); c = errones(size(x)); figure(n); fill(x,y,c); title([num2str(n) '-sided polygon']); text(0,0,['error = ' num2str(err)]); axis off; theta0 = linspace(0,2pi,100); x = cos(theta0); y = sin(theta0); hold on; plot(x,y,'r-','LineWidth',3); % subfunction: only called withing approxpi() function p = perimeter(radius,n) p = n2radiussin(pi/n);

Sheet Page 2 break return error('my own help message') pause find(X) all(X) any(X) function runapproxpi() flag =1; while(flag>0) disp('------------------------------------------------------') n = input('Enter the number of sides (less than 3 to exit): '); if(n >= 3) [approx,ex,err]=approxpi(n); disp([num2str(n) '-sided error: ' ... num2str(err) ' (' num2str(approx) ' ~ ' num2str(ex) ')']) disp('------------------------------------------------------') else flag = 0; end end for n=1: disp(n) end for n=1:2: disp(n) end for n=20:-1: disp(n) end Nlist=[2 7 19 88]; for n = nlist disp(n) end A=rand(5) [I,J]=find(A<0.02) [I,J]=find(A>0.8) isvarname(str) mystr = โ€˜a = 5;โ€™ eval(mystr);