Array indices: using function handles and fminsearch

4 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2020-9-19
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 个评论
Walter Roberson
Walter Roberson 2020-9-19
looks plausible.
More compact:
return_diag = @(alpha) diag(exp(-alpha*(0:N-1)))

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by