learningMatlab

Worked solution

Plotting / Fitting with a model curve

The aim is to plot and fit data to achieve something like the following:

  1. The file summaryData.mat contains data to work with. At the command prompt, do the following:

    load('summaryData.mat') % will load "data"
    data  % find out what's in it.
    
  2. Plot data, using the numbers in the first column as the x-values, the second column as the y-values.

    figure
    plot(data(:,1) , data(:,2), 'o', 'markersize',20, 'markerfacecolor', 'b')
    xlabel('Orientation (deg)')
    ylabel('p(CW responses)')
    % and save a copy for your records
    % help print
    % help gcf
    % ... to see why/how the following line works:
    print(gcf, 'myFigure.pdf', '-dpdf')
    
  3. A “nice” mathematical function / curve, that has such a shape and can be controlled with two convenient parameters is the cumulative version of the normal distribution (or Gaussian curve).

    x = -10:0.2:10; % many x values -10....+10
    % plot the CUMULATIVE / s-shaped function with mu=0, sigma=3
    c = normcdf(x, 0, 3);
    figure, plot(x, c , 'r', 'linewidth',2);
    xlabel('x values'); ylabel('y values'); title('normal CDF: \mu=0, \sigma=3');
    
  4. The 0 and 3 in the above example correspond to the mean (µ) and standard deviation (σ) of a normal distribution. Try plotting the CDF curve for σ = 1 (magenta curve) and σ = 5 (cyan) on the same plot. Then try changing µ, say µ = -2.5 (green) and µ = +3.4 (blue). What happens to the curves?

    x = -10:0.2:10; % many x values -10....+10
    % plot the CUMULATIVE / s-shaped function with other values
    figure
    subplot(1,2,1)
    plot(x, normcdf(x, 0, 3) , 'r', 'linewidth',2);
    hold on
    plot(x, normcdf(x, 0, 1) , 'm', 'linewidth',2);
    plot(x, normcdf(x, 0, 5) , 'c', 'linewidth',2);
    title('changing \sigma')
    subplot(1,2,2)
    plot(x, normcdf(x, 0, 3) , 'r', 'linewidth',2);
    hold on
    plot(x, normcdf(x, -2.5, 3) , 'g', 'linewidth',2);
    plot(x, normcdf(x, +3.4, 3) , 'b', 'linewidth',2);
    title('changing \mu')
    
  5. The fitting problem is: we’d like to know the “best” combination of µ and σ, such that the smooth curve they describe gets as close as possible to the data points. “Close” here means: in such a way that the squared error between the data and the corresponding points on the smooth curve is minimal… the least squares solution.

  6. Before we can hand over the fitting to matlab we need to do the following:

Back to problem description

Back to the description / problem set