0

The following code runs fine and gives the accurate result.

c1...c5 are known constants, and x(1)...x(5) (anonymous vector) are unknown variables which to be fitted by fminsearch using the least square method. (t,y) is the given data (curve) to fit the equation, myfunc is a ode45 function saved in a separate .m file.

% run the solver
options = optimset('MaxFunEvals',10000,'MaxIter',10000,'Display','iter');
[x,fval,exitflag,output] = fminsearch(@(x) Obj(x,initial_p,c1,c2,c3,c4,c5,c6,t,y),x0,options);

function F = Obj(x,initial_p,c1,c2,c3,c4,c5,c6,t,y)
    p = myfunc(x(2:end),initial_p,t,c1,c4);
    yt = mainfunc(x,p,c1,c2,c3,c4,c5,c6);
    F = sqrt(sum((yt-y).^2));
    disp(x);
end

function yt = mainfunc(x,p,c1,c2,c3,c4,~,~)
    yf = c1*c2*c3*c4*sqrt(p);
    yt = x(1)+yf;
end

But error occurs (Assignment has more non-singleton rhs dimensions than non-singleton subscripts) when I rewrite mainfunc (all else being same):

function yt = mainfunc(x,p,c1,c2,c3,c4,c5,c6)
    ys = c1*c3*(c5/(c6*sqrt(p)));
    yf = c1*c2*c3*c4*sqrt(p);
    yt = x(1)+ys+yf;
end

p is a curve (t,p) coming from ode45 in myfunc, it is working fine in the first version of code so no problem there. Is having two terms with sqrt(p) in mainfunc causing the problem?

ShadowWarrior
  • 180
  • 1
  • 12
  • 1
    If `p` is a vector, you probably mean `./` instead of `/`. – Cris Luengo Oct 14 '18 at 13:53
  • It worked, thanks. Should I use `.*` instead of `*` in the assignment for `yf`? – ShadowWarrior Oct 14 '18 at 22:38
  • 1
    For scalar multiplication it doesn’t matter. If you are multiplying two vectors element-wise then you do need that. Copy-paste the operations to your command window one by one, and look at what they do and what they produce, make sure that matches your expectation. – Cris Luengo Oct 14 '18 at 23:23
  • So, for scalar-vector division `./` is necessary, but for scalar-vector multiplication `.*` is not needed? I'm new to Matlab and would like to keep consistency in my code for future reference, hence asking. – ShadowWarrior Oct 14 '18 at 23:47
  • 1
    Right. If one of the arguments is a scalar, then `*` and `.*` do the same thing. But that is not true for division. If the right-hand-side argument is a vector/matrix, then you get the matrix (pseudo-)inverse. Multiplication is symmetric (permutes), division is not. – Cris Luengo Oct 15 '18 at 00:13
  • Thank you for clearing that up, highly appreciate it. – ShadowWarrior Oct 15 '18 at 03:06

0 Answers0