Array indices: using function handles and fminsearch

I have the following code:
P = randn(50);
for i = 1:length(P)
vec{i} = @(alpha)exp(-(i-1)*alpha);
end
G = @(p)p(1)*diag(vec(p(2)));
fun = @(p)norm(eye(50) - G(p)*P);
p0 = [0 0];
[p, fval] = fminsearch(fun, p0)
The idea is essentially to minimize the 2-norm of the matrix . On executing this, I get the following error:
Array indices must be positive integers or logical values.
Error in @(p)p(1)*diag(vec(p(2)))
Error in @(p)norm(eye(50)-G(p)*P)
Error in fminsearch (line 200)
fv(:,1) = funfcn(x,varargin{:});
Since the dimension of the matrix G is quite large, it is not possible for me to hard-code the diagonal entries in the diag( ) function, which is why I'm using the cell array of function handles.
I have tried replacing the variable alpha with p(2) directly, and a couple of other variations on this. All of these give me the same error. I have a feeling that the error is elementary, but since I'm new to using function handles, I am unable to rectify this. I have seen questions on similar lines, but am not able to find a way to adapt their solutions to mine.

 Accepted Answer

vec is a cell array. vec(expression) asks to index the cell array at the expression. But the expression is a floating point number.
If by chance the expression were positive number in range then the result would be a scalar cell, and diag of a cell is not valid.
If you have a cell array of functions then MATLAB does not provide any direct syntax to invoke each handle in turn on the input. You would need to loop, either explicitly or using cellfun.

3 Comments

Thank you for the quick reply. I have a couple of further questions. Using a cell array will lead me to further problems later on as I'm also performing multiplication before minimizing. Creating a matrix of function handles isn't possible, but a workaround is outlined here. Following this workaround, I have the following code:
function D = return_diag(alpha, N)
D = zeros(N);
for i = 1:N
D(i, i) = exp(-(i-1)*alpha);
end
end
P = randn(50);
D = @(alpha) return_diag(alpha, 50);
fun = @(p)norm(eye(50) - p(1)*D(p(2))*P);
p0 = [0 0];
[p, fval] = fminsearch(fun, p0)
I am getting results for this, and I'm hoping that this code is actually correct and follows the principle of a function handle returning a matrix/nonscalar array. Would like to get confirmation on it though.
Thank you.
looks plausible.
More compact:
return_diag = @(alpha) diag(exp(-alpha*(0:N-1)))

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!