%Lab 22 Solutions %MatLab - Using M-files, %loading files and plotting %Patrick D. Schmid clear; %load the text file %note that the current directory in MatLab has to be set to the directory %containing this m file and the data file load data.txt; %extract the x and y columns from the data %note that MatLab uses 1 as smallest array index (in contrast to C++!) xdata = data(:,2); ydata = data(:,3); %%display the read data and then the extracted column vectors data xdata ydata %run a linear regression over our data %note that the 1 at the end means that we are looking for a polynominal of %the sort: c * x^1 + b * x^0 coeff=polyfit(xdata, ydata, 1); %based on the equation above, m is stored in the first array index, b in %the second. Hence with y = m * x + b, we get yline=coeff(1)*xdata+coeff(2); %Plot our data %Contrary to the assignment, this solution plots all charts asked for with %the same m-file, but in different figures. It also adds labels and a %legend %first plot objective: a plot of the x and y data using red x's and the best fit %line using a blue line figure(1); plot(xdata, ydata, 'ro', xdata, yline, 'b-'), title('1) ydata and yline in same figure'), xlabel('xdata'), ylabel('y') legend('original data', 'linear regression'); %second plot objective: red x data points are on one Figure and the blue line is on %another Figure figure(2); plot(xdata, ydata, 'ro'), title('2) ydata '), xlabel('xdata'), ylabel('ydata') legend('original data'); figure(3); plot(xdata, yline, 'b-'), title('2) yline'), xlabel('xdata'), ylabel('yline') legend('linear regression'); %third chart: red x data points are on one subplot of a Figure and the blue %line is on another subplot of the same Figure. figure(4); subplot(2,1,1), plot(xdata, ydata, 'ro'), title('3) ydata '), xlabel('xdata'), ylabel('ydata'), legend('original data'); subplot(2,1,2), plot(xdata, ydata, 'b-'), title('3) yline'), xlabel('xdata'), ylabel('yline'), legend('linear regression');