MATLAB: Does this nlinfit of a cos^2 not work? (Malus law for polaroïd filters)

cosmalusnlinfit

I have a list of measured intensities (to test Malus law) and i'd like to fit this to a*cos(angle)^2. This should give me the value of a. The value it gives me is way off from what it should be, and the variance is huge. What am i doing wrong?
I=[0.0 0.9 2.4 4.4 7.4 10.5 13.3 15.4 16.5 16.7 16.0 14.8 11.9 9.3 6.8 4.2 2.1 0.5 0.0 0.5 1.9 4.2 6.4 9.4 12.6 14.6 15.9 16.6 16.4 14.8 12.5 10.0 6.5 4.2 1.7 0.5];
Theta= diag(ones(length(I)));
for i=1:length(I);
Theta(i) =(i-1)*10/180*pi+3.1415/2; % the 10 stands for 10 degrees
end
Cos2 = cos(Theta).^2;
funct = @(a,x)(a(1)*cos(x).^2);
B0=17;
[B R J covB]=nlinfit(Cos2,I,funct,B0);
x=1.5:0.1:(2*pi+1.5);
hold on
plot(Theta,I,'bo');
plot(x,funct(B,x));

Best Answer

Your independent variable is ‘Theta’, not ‘Cos2’. (You also don’t need a loop to generate ‘Theta’.)
This (corrected) version of your original code works, and gives a good visual fit:
I=[0.0 0.9 2.4 4.4 7.4 10.5 13.3 15.4 16.5 16.7 16.0 14.8 11.9 9.3 6.8 4.2 2.1 0.5 0.0 0.5 1.9 4.2 6.4 9.4 12.6 14.6 15.9 16.6 16.4 14.8 12.5 10.0 6.5 4.2 1.7 0.5];
Theta = [0:length(I)-1]*10/180*pi+pi/2;
funct = @(a,x)(a(1)*cos(x).^2);
B0=17
[B R J covB]=nlinfit(Theta,I,funct,B0);
x=1.5:0.1:(2*pi+1.5);
figure(1)
plot(Theta,I,'bo');
hold on
plot(x,funct(B,x));
hold off