How to select element of matrix that is created with function handle ?
18 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2015-10-16
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 个评论
Stephen23
2015-10-16
编辑:Stephen23
2020-4-20
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
2015-10-16
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.
更多回答(1 个)
Guillaume
2015-10-16
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}}))
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!