Using a vector of coefficients in 'fittype'

4 views (last 30 days)
Hi everyone,
I am trying to fit some lab data, but the number of coeffiecients is very big and I prefer to keep it as a vector. However, I cannot seem to make it work so I tried a simplified version from the manual:
function y = piecewiseLine(x,a,b,c,d,k)
y = zeros(size(x));
for i = 1:length(x)
if x(i) < k
y(i) = a + b.* x(i);
else
y(i) = c + d.* x(i);
end
end
end
Then:
x = [0.81;0.91;0.13;0.91;0.63;0.098;0.28;0.55;...
0.96;0.96;0.16;0.97;0.96];
y = [0.17;0.12;0.16;0.0035;0.37;0.082;0.34;0.56;...
0.15;-0.046;0.17;-0.091;-0.071];
ft = fittype(@(a, b, c, d, k, x)piecewiseLine(x,a,b,c,d,k), 'coefficients',{'a', 'b', 'c', 'd', 'k'});
f = fit( x, y, ft, 'StartPoint', [1, 0, 1, 0, 0.5] )
This works fine.
If I try to turn the coefficients into a vector:
function y = piecewiseLine(x,V)
a=V(1);
b=V(2);
c=V(3);
d=V(4);
k=V(5);
y = zeros(size(x));
for i = 1:length(x)
if x(i) < k
y(i) = a + b.* x(i);
else
y(i) = c + d.* x(i);
end
end
end
And then do the fitting again like this:
x = [0.81;0.91;0.13;0.91;0.63;0.098;0.28;0.55;...
0.96;0.96;0.16;0.97;0.96];
y = [0.17;0.12;0.16;0.0035;0.37;0.082;0.34;0.56;...
0.15;-0.046;0.17;-0.091;-0.071];
ft = fittype(@(V, x)piecewiseLine(x,V), 'coefficients',{'V'});
f = fit( x, y, ft, 'StartPoint', [1, 0, 1, 0, 0.5] )
Then I get the following error:
Expression piecewiseLine(x,V) is not a valid MATLAB expression, has non-scalar coefficients, or cannot be evaluated
Is there a way to use a vector (nx1) of coefficients when fitting instead of n coefficients??
Thanks,
Andrea

Answers (1)

Sai Sri Pathuri
Sai Sri Pathuri on 18 Jul 2019
The coefficients to fittype function cannot be passed as a vector. In order to get nearly same output, you can use lsqcurvefit function from Optimization Toolbox.

Categories

Find more on Linear and Nonlinear Regression in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!