% Class 4 - Last of Matlab Bootcamp % Coded by NFR on 9.5.2109 % Topics today % 1) More for/while loop practice % 2) Plotting % 3) Functions (variables, structure) % 4) Class example % % Example of loops % % For loop to calculate pi from Leibniz series % clc close all % This closes previous figure windows n = 100000; % # of iterations val = 0; for i = 1:n d = i*2-1; if mod(i,2) == 0 % even val = val - 1/d; else % odd values val = val + 1/d; end end fprintf('Estimated value of pi is %.5f\n',val*4) % Same formula, but use while loop to exit % based on a tolerance criteria tol = 0.0000001; % % Remember this is the difference between % the last calculated estimate and the current estimate tolcheck = 1; % intialize check value count = 1; val = 0; while tolcheck > tol d = count*2-1; oldval = val; if mod(count,2) == 0 % even val = val - 1/d; else % odd values val = val + 1/d; end count = count + 1; tolcheck = abs(oldval-val); end count pi_e = val*4 % PART II - Plotting % Import data from the saved excelfiles WD = readmatrix('weather.xlsx'); PD = readmatrix('IA pop data.xlsx'); % Simple plot of avg vs. day X = WD(3:end,1); % days Y = WD(3:end,3); % avg temp plot(X,Y,'+k') xlabel('Days in May 2017') ylabel(['Avg Temperature (',char(176),'C)']) title('This is my plot!') text(7,50,'HELLO!') hold on % this specifies, next plot command % goes on top of the current plot plot(15,50,'ob') hold off % turn off hold when plot is complete % figure % this opens a new figure window for next plot % Plot the population data X = PD(2:end,1); % years Y = PD(2:end,2); % population plot(X,Y,'o:') xlabel('Years') ylabel('Population in IA') % figure semilogy(X,Y,'o:') xlabel('Years') ylabel('Population in IA') % How to use error bars % weather data, error bars will show high and low data X = WD(3:end,1); % days Y = WD(3:end,3); % avg temp lowvec = WD(3:end,2); % low temp highvec = WD(3:end,4); % high temps figure errorbar(X,Y,Y-lowvec,highvec-Y) xlabel('Days in May 2017') ylabel(['Avg Temperature (',char(176),'C)']) saveas(gcf,'Plot1.jpg') % Let's say you want multiple plots on the same screen % Use subplots figure subplot(1,3,1) plot(X,Y) title('Avg. temp') subplot(1,3,2) plot(X,lowvec,'k:o') title('Low temp') subplot(1,3,3) plot(X,highvec) title('High temp') % Discrete data (bar chart) % Dr. Reuel will post a couple examples % of bar charts DS = readmatrix('skillsurvey.xlsx'); set(gca,'YTickLabel',{'A' 'B' 'C' 'D' 'E'}) figure bar(DS(:,4)) % 3D data set figure Zdata = readmatrix('elevation.csv'); %contourf(Zdata) %surface(Zdata) % % A few important reminders about functions % 1) You can create a separate file as the function % 2) You can also write a function % as a 'local function' % this is typically at end of code % 3) You can also define an anonymous function % This is defined much like a variable % in the main block of code % Example of an anonymous function afunc1 = @(x) sin(x)+2-3; output1 = afunc1(2); figure fplot(afunc1,[0 5])