% File: directionFieldPlot.m Version 1 % % A. O. Hausknecht Spring 2012 % Mathematics Department, UMass Dartmouth % % directionFieldPlot(dydxInline, xyMin, xyMax, xyN, useArrows) % % PURPOSE: Automates the plotting of the direction field % of a first-order ODE written in the form dy/dx = f(x,y) % over a square in the xy-plane % % ITS PARAMETERS: % dydxInline: The f(x,y) represented as an inline function. % xyMin, xyMax: limits of the plotting domain for both x and y. % xyN: The number arrows or line segments in each direction. % useArrows: Plots arrows instead of line segments % when true or 1 is passed. % function directionFieldPlot(dydxInline, xyMin, xyMax, nXY, useArrows) if (xyMin == xyMax) "Error: xyMin == xyMax; Will decrease xMin by 2 and increase xMax by 2." xyMin = xyMin - 2; xyMax = xyMax + 2; elseif (xyMin > xyMax) "Error: xyMin > xyMax; Will reverse xyMin and xyMax." temp = xyMax; xyMax = xyMin; xyMin = temp; end if (nXY < 4) n = 4; "Error: nXY < 4; Will assume nXY = 4." end % Generate a mesh of points to be evaluated [X, Y] = meshgrid( linspace(xyMin, xyMax, nXY) ); DY = dydxInline(X,Y); DX = ones(size(DY)); % Scale the length of the arrows or line segments xyDelta =(xyMax - xyMin)/nXY; DW = sqrt(DY.^2 + DX.^2)*3/xyDelta; % Plot the direction field h = quiver(X, Y, DX./DW, DY./DW, 'linewidth', 2); % Plot using arrows or line segments if (useArrows) set(h, 'showarrowhead', 'on'); else # use line segments set(h, 'showarrowhead', 'off'); end % Set the viewing rectangle and add an axes axis([xyMin xyMax xyMin xyMax]); line([xyMin xyMax], [0 0], 'linewidth', 3); line([0 0], [xyMin xyMax], 'linewidth', 3); xlabel('x'); ylabel('y'); end