%POLYFIT_NOISE: Matlab script file to fit and plot a quadratic polynomial % to data from a quadratic with noise added. % % Usage: >> polyfit_noise % % inputs: none % % outputs: a plot containing the original data, the noisy data, % the true curve, and the curve fitted to the noisy data. % file: ~/matlab/courses/NumerComput/polyfit_noise.m % % sample M-file for Intro Numer Comput I class % % C.G. (11-01) % % generate true and noisy points, and plot them % x = linspace( -1, 1, 10 ) ; % 10 equally spaced points in [-1,1] y = x.^2 ; % 'y' values at those points clf ; hold on ; box on % prepare current figure window plot( x, y, 'bo' ) % plot true data points as blue circles lev = .2 ; % noise level yn = y + lev * (2*rand(size(y))-1) ; % add uniform noise from [ -lev, lev ] plot( x, yn, 'rd' ) % plot noisy data points as red diamonds % % fit noisy data and plot fitted curve along with true curve % p = polyfit( x, yn, 2 ) ; % coefficients of fitted polynomial xx = linspace( -1, 1, 100 ) ; % 'x' points for plotting curves yy = polyval( p, xx ) ; % 'y' values of fitted quadratic plot( xx, yy, 'r--' ) % plot fitted curve as red dashed plot( xx, xx.^2, 'b-' ) % plot true curve as blue solid axis( [ -1 1 -lev 1+lev ] ) % specify 'x', 'y' axis limits % plot horizontal and vertical axes (black, solid) for reference/appearance plot( [ -1 1 ], [ 0 0 ], 'k-', [ 0 0 ], [ -lev 1+lev ], 'k-' ) % 'x', 'y' axis labels xlabel( 'x', 'FontSize', 12 ) ylabel( 'y', 'FontSize', 12 ) % give the noise level in the title for annotation/information title( [ 'lev = ', num2str(lev) ], 'FontSize', 15 )