Minimization of Functional
2 views (last 30 days)
Show older comments
| So I have a function, which is supposed to take a data matrix break it down into its respective column matrices. Then it defines a function by summing the distance from some input point, each one of these column matrices to some point X. I then nested this program so that I could attempt to minimize this function, however when I do this things start to go funny.
Firstly, often I get message,
"Warning: Gradient must be provided for trust-region
algorithm;
using line-search algorithm instead.
> In fminunc at 347
In runMedian at 2
Local minimum possible.
fminunc stopped because the size of the current step is less than
the default value of the step size tolerance."
If I try and use fminunc instead of fminsearch. So should I be using one over the other here?
Secondly and more disturbing is that this often returns a non-sensical answer. For example, if I give it the data matrix: A=[2 -2; 0 0], and let X0=0 the answer returned to me is: X =
0.0041 -0.0017
0.0017 0.0042
fval =
0.0046
Which is completely non-sensical because since we broke A into two column matrixs, [10;0] and [-10;0] the operation of X-A(n) is not defined if X is a 2x2 matrix. The answer should be X=0 by the way. Any suggestions?
My code is:
function[X,fval] = runMedian(X0,A) %#ok<INUSD>
[X,fval] = fminsearch(@Median, X0);
function[Y] = Median(X)
numberColumns = size(A,2);
a = cell(1, numberColumns);
for nc = 1:numberColumns
a{nc} = A(:,nc); % Note the curly brackets for a{nc}
end
for nc = 1:numberColumns
y(nc) = norm(X-(a{nc}));
end
Y = sum(y);
end
end
Thanks
0 Comments
Answers (1)
Walter Roberson
on 16 Jul 2011
Instead of using nested functions, please try using an anonymous function to pass the extra argument:
function[X,fval] = runMedian(X0,A)
[X,fval] = fminsearch(@(X) Median(X,A), X0);
end
function[Y] = Median(X,A)
numberColumns = size(A,2);
a = cell(1, numberColumns);
for nc = 1:numberColumns
a{nc} = A(:,nc); % Note the curly brackets for a{nc}
end
for nc = 1:numberColumns
y(nc) = norm(X-(a{nc}));
end
Y = sum(y);
end
I have not checked the rest of your logic.
2 Comments
Walter Roberson
on 16 Jul 2011
There doesn't seem to be any point to going through the two independent loops or in forming the cell array. Each a{nc} is used only once, so your function can be:
numberColumns = size(A,2);
y = zeros(numberColumns,1);
for nc = 1:numberColumns
y(nc) = norm(X-A(:,nc));
end
Y = sum(y);
Or alternately, it could be the single line,
Y = sum(arrayfun(@(nc) norm(X-A(:,nc)),1:size(A,2));
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!