Array indices: using function handles and fminsearch

조회 수: 10 (최근 30일)
Ram Padmanabhan
Ram Padmanabhan 2020년 9월 19일
댓글: Ram Padmanabhan 2020년 9월 20일
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