How to select element of matrix that is created with function handle ?
5 ビュー (過去 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!