## Error using fminunc with array as function output and multiple inputs

Mikkel Mortensen

### Mikkel Mortensen (view profile)

さんによって質問されました 2019 年 2 月 27 日

### Alan Weiss (view profile)

さんによって 回答されました 2019 年 2 月 27 日
We are trying to optimize three parameters using fminunc.
Our function contains two for-loops and gives us a probability over time in a vector.
Our parameters for optimization are used in this function as x(1), x(2), x(3)
function P = probabilityFunction(x,T,Tmed)
P = ones(length(T),1)*x(3);
for t=0:T(end)
numPills = sum(Tmed < t);
for i=1:numPills
P(t) = P(t) - x(1)*exp(-x(2)*(t-Tmed(i)));
end
end
end
When we try to run the fminunc, it gives us the error "Supplied objective function must return a scalar value"
We call the fminunc like this:
% pooling the data into one array and sorting
Tmed = [deltaT_mo deltaT_ev]';
Tmed = sort(Tmed);
T = (1:max(Tmed))';
noDrug = 0.5;
E = 0.0025;
v = 0.009;
x0 = [E; v; noDrug];
%%
f = @(x)probabilityFunction(x,T,Tmed);
%%
[x,fval] = fminunc(f,x0);
Should we use another function or is there a way to make the probability as a scalar?
- Thanks

#### 0 件のコメント

サインイン to comment.

## 1 件の回答

### Alan Weiss (view profile)

2019 年 2 月 27 日

It is not clear what you are trying to do. Your P(x,T,Tmed) is not a scalar, so it is not clear what it means to minimize it.
You might be looking for a least-squares minimization, something like sum(P.^2). If so, you can take your existing objective function and ask lsqnonlin to minimize it. Or you can reformulate your objective function as the sum of squares. For details, see Nonlinear Data-Fitting.
Alan Weiss
MATLAB mathematical toolbox documentation

#### 0 件のコメント

サインイン to comment.