Constructing a matrix of function handles
조회 수: 49 (최근 30일)
이전 댓글 표시
Is there a way to recursively construct a matrix of function handles? It is possible to construct a matrix of function handles as follows
GS=@ (x)[states{1}(x)'*states{1}(x) states{1}(x)'*states{2}(x);
states{2}(x)'*states{1}(x) states{2}(x)'*states{2}(x)],
where states{i}(x) are function handles themselves. However, as I would like to construct this matrix for arbitrary n (say n=100) I would like to create the gram matrix in a for loop. I tried to create my own function that takes as input the n vectors and constructs the Gram matrix of their overlaps, i.e. G(i,j)=@ (x) states{i}(x)'*states{j}(x).
This clearly does not work since one cannot then pass the argument into G; the issue being that matlab requires a pair of indices in the command G() and not the argument of the function handle. However it is clearly possible to create a matrix of function handles as shown above, and yet not possible to create it recursively. Does anyone know of a workaround for this.
댓글 수: 2
Star Strider
2016년 9월 23일
‘Here states{i}(x) are function handles themselves. ’
It would help if we have all the relevant parts of your code, and specifically what ‘states’ actually are. Those don’t look like valid function calls to me.
You can certainly create a matrix of function calls. Anonymous functions have some restrictions on what you can do with them.
Steven Lord
2016년 9월 23일
They are valid function calls. The states variable is a cell array each cell of which contains a function handle. First you index into the cell array to retrieve a function handle, then you evaluate that function handle.
states = {@sin, @cos, @tan};
% Two step approach
cosineHandle = states{2}
cosineHandle(pi)
% One step approach
states{2}(pi)
% Alternate one step approach
cos(pi)
답변 (1개)
Steven Lord
2016년 9월 23일
You cannot create a nonscalar array of function handles.
You can create a function handle that returns a nonscalar array, but that's different.
You can create a cell array each cell of which contains a function handle, but that's also different.
For the application you described, having a function handle that returns a nonscalar array is probably going to be the easiest.
f = @(x) x(:); % The output is of size [numel(x) 1]
GS = @(x) f(x)*f(x).'; % The output is of size [numel(x) numel(x)]
x = 1:10;
multiplicationTable = GS(x)
댓글 수: 2
Steven Lord
2016년 9월 23일
Can you show a specific example where you construct the states cell array of function handles and compute GS for a specific vector? Your example doesn't need to use n = 100; something like n = 3 or n = 4 should serve to explain more clearly your ultimate goal.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!