No BSD License  

Highlights from
fitting

from fitting by morteza ahmadi
fitting with any function

n_fit.m
clc


%% input matrix

xx=[1 2 3 4 5 6];
yy=[1 2 3 4 5 6];

%% process
% Write function (a*sin(x)+b+...) :
% a*sin(x)+b*cos(x)+c*x^2
% Input X matrix:
% xx
% Input Y matrix :
% yy
% 
% a =
% 
%     0.7113
% 
% 
% b =
% 
%    -1.1164
% 
% 
% c =
% 
%     0.2169
% 
%  
%                                                             2
%                   0.71126 sin(x) - 1.1164 cos(x) + 0.21686 x
% 

%% main program
syms x a b c d e f g h

ff=input('Write function (a*sin(x)+b+...) :\n');
xx=input('Input X matrix:\n');
yy=input('Input Y matrix :\n');


E=0;
for i=1:size(xx,2)
    ee(i)=subs(ff,x,xx(i))-yy(i);
    E=E+ee(i)^2;
end

switch  length(symvar(findsym(E)))
    case 1
        [a]=solve(diff(E,a));
        a=double(a)
        pretty(vpa(subs(ff,{'a'},{a}),5))


    case 2
        [a,b]=solve(diff(E,a),diff(E,b));
        a=double(a)
        b=double(b)
        pretty(vpa(subs(ff,{'a','b'},{a,b}),5))

    case 3
        [a,b,c]=solve(diff(E,a),diff(E,b),diff(E,c));
        a=double(a)
        b=double(b)
        c=double(c)
        pretty(vpa(subs(ff,{'a','b','c'},{a,b,c}),5))

    case 4
        [a,b,c,d]=solve(diff(E,a),diff(E,b),diff(E,c),diff(E,d));
        a=double(a)
        b=double(b)
        c=double(c)
        d=double(d)
        pretty(vpa(subs(ff,{'a','b','c','d'},{a,b,c,d}),5))

    case 5
        [a,b,c,d,e]=solve(diff(E,a),diff(E,b),diff(E,c),diff(E,d),diff(E,e));
        a=double(a)
        b=double(b)
        c=double(c)
        d=double(d)
        e=double(e)
        pretty(vpa(subs(ff,{'a','b','c','d','e'},{a,b,c,d,e}),5))

    case 6
        [a,b,c,d,e,f]=solve(diff(E,a),diff(E,b),diff(E,c),diff(E,d),diff(E,e),diff(E,f));
        a=double(a)
        b=double(b)
        c=double(c)
        d=double(d)
        e=double(e)
        f=double(f)
        pretty(vpa(subs(ff,{'a','b','c','d','e','f'},{a,b,c,d,e,f}),5))

    case 7
        [a,b,c,d,e,f,g]=solve(diff(E,a),diff(E,b),diff(E,c),diff(E,d),diff(E,e),diff(E,f),diff(E,g));
        a=double(a)
        b=double(b)
        c=double(c)
        d=double(d)
        e=double(e)
        f=double(f)
        g=double(g)
        pretty(vpa(subs(ff,{'a','b','c','d','e','f','g'},{a,b,c,d,e,f,g}),5))

    case 8
        [a,b,c,d,e,f,g,h]=solve(diff(E,a),diff(E,b),diff(E,c),diff(E,d),diff(E,e),diff(E,f),diff(E,g),diff(E,h));
        a=double(a)
        b=double(b)
        c=double(c)
        d=double(d)
        e=double(e)
        f=double(f)
        g=double(g)
        h=double(h)
        pretty(vpa(subs(ff,{'a','b','c','d','e','f','g','h'},{a,b,c,d,e,f,g,h}),5))
end






Contact us at files@mathworks.com