% Linear regeression with non-zero intercept: that is curve fit equation does
% not necessarily pass through origin. Use least-squares method. OCTAVE solver
% are ols: Ordinary least squares estimation, gls: Generalized least square

% Load the data from our text file
  data = load('sigmaDia.txt');
% Extract dependent variable (first column) / independent variable (second col)
  x = data(:, 2);
  y = data(:, 1);
  q = zeros(2,1);
% Count number of data points
  N = length(x);
% Add a column of all ones before to vector x. A is now a matrix with 2 columns
% actual value is stored in second column
  A = [ones(N, 1), x];
% Calculate curve-fit coefficients, pinv(x) = pseudoinverse of x
  q = (pinv(A' * A)) * A' * y;
  
  hold on;
% Plot raw data
  plot(x, y, 'o');
% Plot curve-fit data
  plot(A(:,2), A * q, '-');
  
  str = strcat("y = ", num2str(sprintf('%8.3f', q(2))), " * x + ", num2str(sprintf('%8.3f', q(1))));
  legend('Raw Data', str, "location", 'northwest');
  
  xlabel('Bar Diameter [mm]'); ylabel('UTS [MPa]');
% Create PNG file from plot  
  print -dpng diamSigma.png -color -landscape;
  hold off;
  
% fprintf('Program paused. Press enter to continue.\n');
% pause;