0

I have two arrays x and y, and would like to fit an exponential to them with a(1) and a(2) as fitting parameters. I wrote a test code as follows:

k=6.63e-34*3e8/1.38e-23
x=[1;2;3;4;5;6;7;8;9;10]
y=[280;320;369.22772;391.25743;414.74257;
   439.75248;466.06931;493.60396;523.87129;530]
w=[0;0;1;1;1;1;1;1;1;0] //weighting

//fitting function
function y=yth(x,a)
    y=a(1)*exp(-k/x/a(2))
endfunction

//initial parameter guess
a0=[1.0,1.0]

function e=myfun(a,x,y,w)
    e=w.*(yth(x,a)-y)
endfunction

[f,xopt,gopt]=leastsq(list(myfun,x,y,w),a0) 

And I am having the following errors

[f,xopt,gopt]=leastsq(list(myfun,x,y,w),a0) 
!--error 9 
Inconsistent subtraction.
at line       2 of function fn called by :  
at line       2 of function %opt called by :  
at line      92 of function leastsq called by :  
[f,xopt,gopt]=leastsq(list(myfun,x,y,w),a0)
user2993263
  • 55
  • 1
  • 7
  • I don't know scilab, but I'm curious what the variables `yrm` and `wrm` are; it appears those are not defined (but `y` and `w` are). –  Jul 22 '14 at 16:02

2 Answers2

0

This is not my cup of tea, but your mistake is in the yth function

function y=yth(x,a)
    y=a(1)*exp(-k/x/a(2))
endfunction

The division of k is not element-wise but also transposes the matrix.

Short demo

k = 5
x = randn(10,1)

// You are doing this in your code
disp( k / x)

// But you are probably wanting to do this
disp( k ./ x )

Solution

Once again, this is not my cup-of-tea, but it at least solves the error.

function y=yth(x,a)
    y=a(1)*exp(-k./x/a(2))
endfunction
spoorcc
  • 2,907
  • 2
  • 21
  • 29
0

I did something similar and got rid of the error by providing column vectors instead of row vectors like this:

[f,xopt,gopt]=leastsq(list(myfun,x',y',w),a0) 
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47