0
votes

I have a function saved as a 'calculateResults.m' in which the function 'ode45' is nested:

function y = calculateResults (concV, ksV, xTrace)
options = odeset('NonNegative', [1:size(concV,2)], 'RelTol', 1e-6, 'AbsTol', 1e-12);
[x,y] = ode45(@(t, cY)odeSet(t, cY, ksV), xTrace, concV, options);

I would like to use this function as a fittype:

ft = fittype('calculateResults( concV, ksV, x )','independent',{'x'});

But doing this causes the error:

Error using fittype/testCustomModelEvaluation (line 12) Expression calculateResults( concV, ksV, x ) is not a valid MATLAB expression, has non-scalar coefficients, or cannot be evaluated: Error in fittype expression ==> calculateResults( concV, ksV, x ) ??? Index exceeds matrix dimensions.

My aim is to vary the values of 'concV' in order to fit the function 'calculateResults.m' to some data (x and y):

mdl = fit( x, y, ft);

And finally return the values of concV that best fit the data:

concVCalc = mdl.Coefficients.Estimate; 

Please help! Thank you!

1
Well, the error is rather clear. Somewhere an index exceeds matrix dimensions. Have you already tracked down where that happens? - Adriaan
@Adriaan Evaluating y = calculateResults(concV, ksV, x); independently works fine -suggesting I am doing something fundamentally wrong. Perhaps my syntax is wrong, but I have checked this against the MathWorks example. - Pete
I would try specifying the types of ALL the variables in the expression. You need to tell fit how to interpret concV and ksV. Looks like concV is a "coefficient", and ksV is a "problem" variable? - Peter
@Peter I tried ft = fittype('calculateResults( concV, ksV, x )','independent',{'x'},'coefficient',{'concV'},'problem',{'ksV'}); but the same error persists. - Pete
Adriaan is right. It actually gives you the error, saying that an index exceeds matrix dimensions. Set the debugger to stop on errors, and inspect the values inside calculateResults. - Peter

1 Answers

0
votes

Solved by giving the coefficients as individual variables rather than an array:

  ft = fittype('calculateResultsForFit(x,concV1,concV2,concV3,concV4,concV5,concV6,concV7,concV8,concV9,concV10,concV11,concV12,concV13,concV14,concV15,concV16,concV17,concV18,concV19,concV20)');

    mdl = fit( x', yToFit', ft,'StartPoint',[concV1,concV2,concV3,concV4,concV5,concV6,concV7,concV8,concV9,concV10,concV11,concV12,concV13,concV14,concV15,concV16,concV17,concV18,concV19,concV20],'Lower',zeros(1,20));

Variable ksV now defined inside the function being fitted.