Is there a way to access array elements returned by a function directly
조회 수: 28 (최근 30일)
이전 댓글 표시
Assume this code:
a=magic(4);
then I can do:
a(1,2)
to access the elements of the matrix a. Is there a way to do it directly without associating the variable a with the result of the function magic, that is, something like:
magic(4)(1,2)
?
댓글 수: 0
답변 (2개)
Steven Lord
2021년 6월 14일
What you've written is not valid MATLAB syntax. You could do something close to what you want using a helper function.
valueAt = @(A, varargin) A(varargin{:});
valueAt(magic(4), 1, 2)
M = magic(4) % so you can see what element (1, 2) is
댓글 수: 4
Steven Lord
2021년 6월 14일
It's easy to say how the syntax you described should work in the simple cases that interest you.
It's not nearly so easy to say how it should work in the general case for which we would have to design that feature.
As an example, the eig function has two outputs. The first is a matrix of eigenvectors and the second the corresponding eigenvalues. Suppose I wanted the third eigenvector and eigenvalue? How would you do that with your syntax?
format longg
A = magic(5);
[V, D] = eig(A)
check = A*V(:, 3)-V(:, 3)*D(3, 3)
Now what would you do to get the third eigenvector and eigenvalue using this call to eig?
[V, D] = eig(A, 'vector')
Matt J
2021년 6월 15일
In theory, it is possible to make a function directly indexable using OOP trickery,
>> Magic=IndexableFunction(@magic);
>> Magic{4}(1,2)
ans =
2
It's not worth it...
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!