Help with executing a least square fitting

조회 수: 6 (최근 30일)
Erik Heimbürger
Erik Heimbürger 2017년 5월 16일
답변: Walter Roberson 2017년 5월 16일
Hi I've looked up one of my old .m files and it's been a while since last time I wrote matlab code.
I suspect I'm doing two things wrong here.
1. My "if loops" are not correctly written, I can´t see what im doing wrong here. how should it be written?
2. I can´t use the sign && here. What should i replace it with?
% Executes Least square fitting with matrix method for polynomial
% Entered data: (x,y,deltay,n)
%deltay is the uncertainty in y
%n is the exp for the polynomial highest x-term
%
%Utdata: (A, Deltapar)
%A is the fitting
%Deltapar is the uncertainty in the fitting.
function[A Deltapar] = MKA(x,y,deltay,n)
A = [];
Deltapar = [];
X=[];
%------------------------------------------------------------------------------------------------------------------
% Controls if the matrix format on the indata is in the correct size
if(size(x)(2)~=1)
x=x';
endif
if (size(y)(2)~=1)
y=y';
endif
if(size(deltay)(2)~=1)
deltay=deltay';
endif
%------------------------------------------------------------------------------------------------------------------
% controls if the matrices x,y och deltay have the correct format for the execution for the least square fitting.
if(size(x)(2)==1 && size(y)(2) ==1 && size(deltay)(2)==1)
%------------------------------------------------------------------------------------------------------------------
% Executes the least square fitting if the matrices x and y have the same format.
% If not, return a message that says that the matrices x or y is not of the correct length.
if(length(x)==length(y))
for i=0:n
X=[X x.^i];
end
for
sigma=deltay;
vminus1 = diag(1./sigma.^2);
A = inv(X' * vminus1 * X) * (X' * vminus1 * y);
DeltaA = inv(X' * vminus1 * X);
Deltapar = sqrt(diag(DeltaA));
else
disp('x,y does not have the same length');
endif
%------------------------------------------------------------------------------------------------------------------
% Prints "you have not entered the indata on the correct form."
else
disp('You have not entered the data on the correct form');
endif
%------------------------------------------------------------------------------------------------------------------
Thanks in advance.
Friendly Regards.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 5월 16일
size(x)(2) is not valid syntax in MATLAB. () indexing can never be followed directly by () indexing. You should use size(x,2)

카테고리

Help CenterFile Exchange에서 Data Preprocessing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by