Getting first element of a function output

209 vues (au cours des 30 derniers jours)
Yue
Yue le 18 Mai 2012
Hi everyone,
I am trying to get the value of the first element of an output of a function. For example, The output of my function test is [a1, a2, a3] and I want to get the value of a1 only.
The way I do it is
a = test(input);
result = a(1);
I wonder if there is an easier way to do it. Is there something similar to
result = (test(input))(1);
in matlab?
  1 commentaire
Fabien Fellay
Fabien Fellay le 16 Juil 2020
Now, you can do (the less painful solution so far):
result = table(test(input)).Var1(1);
For example, if you want to do:
A = magic(3);
result = A(2,2);
You can do:
result = table(magic(3)).Var1(2,2);
The following is also possible (but longer and ugly):
result = subsref(magic(3),struct('type','()','subs',{{2,2}}));

Connectez-vous pour commenter.

Réponses (3)

Andrei Bobrov
Andrei Bobrov le 18 Mai 2012
no easier way
result = subsref(test(input),struct('type','()','subs',{{1}}))

Daniel Shub
Daniel Shub le 18 Mai 2012
See this answer about what is missing from MATLAB.
If test is a function you wrote, you could change what it returns. You could also write a wrapper around test:
function a1 = test1(input)
a = test(input);
result = a(1);
end
  1 commentaire
Jan
Jan le 18 Mai 2012
In my opinion this method is easy, clear and efficient.
A modification of the Matlab syntax would be worse due to breaking the backward compatibility. +1

Connectez-vous pour commenter.


Ramuel Safarkoolan
Ramuel Safarkoolan le 17 Nov 2021
[a,~,~]=test(input);
will do the trick

Catégories

En savoir plus sur Statistics and Machine Learning Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by