Array indices: using function handles and fminsearch
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ram Padmanabhan
el 19 de Sept. de 2020
Comentada: Ram Padmanabhan
el 20 de Sept. de 2020
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.
0 comentarios
Respuesta aceptada
Walter Roberson
el 19 de Sept. de 2020
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 comentarios
Walter Roberson
el 19 de Sept. de 2020
looks plausible.
More compact:
return_diag = @(alpha) diag(exp(-alpha*(0:N-1)))
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!