How to select element of matrix that is created with function handle ?
18 views (last 30 days)
Show older comments
Let say we have matrix defined as
A = @(a,n) [a 1 2+1i n*a; 0 1 3+n*1i a; a^2 0 1 a; a 0 0 a];
M1 = @(a)eye(4,4);
for n = 1:10
M1 =@(a) M1(a)*A(a,n); % ?
end
How to select M1(1,4) that is dependent on a?
m14 = @(a)M1(a)(1,4) %doesnt work
0 Comments
Accepted Answer
Walter Roberson
on 16 Oct 2015
select = @(M,r,c) M(r,c);
m14 = @(a) select(M1(a), 1, 4);
But a lot of the time when you have code like that you should just have a routine that asigns M1(a) to a variable and then index the variable as needed.
2 Comments
Stephen23
on 16 Oct 2015
Edited: Stephen23
on 20 Apr 2020
Although this feature is found in some other popular languages, MATLAB does not currently support indexing into indexed variables, or indexing directly after evaluated functions. Although users who have experience with those other languages might want to try to replicate that behavior, keep in mind that it probably makes code slower, as the JIT engine is unlikely to optimize such indexing-via-anonymous-function. Basic indexing will likely be more efficient:
tmp = M1(a);
tmp(1,4)
Although it might have some particular use cases, I would recommend trying to learn to program the MATLAB way, rather than trying to stick with what works in another language.
Guillaume
on 16 Oct 2015
I actually think that the code written by Ole is quite clever. It's a nifty example of functional programming in matlab, and that is indeed pushing the limits of what matlab can do.
I don't think that this code could have been written by somebody new to matlab and certainly not by somebody new to programming.
More Answers (1)
Guillaume
on 16 Oct 2015
First of all, the code you've written does not define any matrix. It defines functions that generate matrices, but until you call the functions, no matrix exist.
Secondly, I'm going to assume that the M1 recursion is intended and that you intend the final M1 to be:
M1 = @(a) eye(4,4)*A(a,1)*A(a,2)*A(a,3)*...*A(a,10)
I'm not sure of the performance impact of the recursion, the workspace of the final anonymous function is going to be huge. You may be better off going with a non-anonymous function that contains a loop.
Anyway, to answer your question, matrix indexing is translated into calls to subsref, so just use that:
m14 = @(a) subsref(M1(a), struct('type', '()', 'subs', {{1 4}}))
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!