How to select element of matrix that is created with function handle ?

조회 수: 9 (최근 30일)
Ole
Ole 2015년 10월 16일
편집: Stephen23 2020년 4월 20일
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

채택된 답변

Walter Roberson
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
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
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
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}}))
  댓글 수: 1
Ole
Ole 2015년 10월 16일
Thank you. The matrix is unknown basically. I need to find the few 'a' that satisfy det(M)=0. M contains only half of the elements of M1.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by