Using return values of functions without storing them?

4 ビュー (過去 30 日間)
Alexander Reichstein
Alexander Reichstein 2011 年 7 月 13 日
Is there an elegant way to save variables by combining commands? Example: Eigenvalues of a 2x2-Matrix, b= [2 4; 9 7]. Compute the eigenvalues using eig(b) which will return 'ans = [-2; 11]'. If I wanted to know only the second eigenvalue and use that in a further reference, I'd have to store the answer of 'eig' - is there a way around this? I'm looking for something like 'z=pi * eig(b)(2,1);' (which doesn't work, because eig(b) is not recognized as a vector) instead of 'q=eig(b); z=pi * q(2,1);' Can anyone help with this?

回答 (2 件)

Teja Muppirala
Teja Muppirala 2011 年 7 月 13 日
As has been noted above, what you are trying to do is not possible. But even when you nest functions inside of each other, MATLAB still has to implicitly create temporary variables in memory.
This will probably surprise you (the second loop is significantly faster):
A = rand(1000);
tic
for n = 1:100
B1 = sum(A.^2);
end
toc
tic
for k = 1:100
tmp = A.^2;
B2 = sum(tmp);
end
toc
isequal(B1,B2)
So the point is, don't worry about creating temporary variables.

Sean de Wolski
Sean de Wolski 2011 年 7 月 13 日
save2 = @(x)x(2,1);
z = pi*save2(eig(b));
Does what you want but is probably not faster.
  4 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 7 月 13 日
@Daniel: I think it's elegant if you're going to use it multiple times; for one or two times - yes; looks kinda lame-o.
Walter Roberson
Walter Roberson 2011 年 7 月 13 日
There is also a way to do it using subsref(), but it is less elegant than Sean's method.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by