Getting first element of a function output

조회 수: 222 (최근 30일)
Yue
Yue 2012년 5월 18일
답변: Ramuel Safarkoolan 2021년 11월 17일
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
Fabien Fellay
Fabien Fellay 2020년 7월 16일
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}}));

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

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2012년 5월 18일
no easier way
result = subsref(test(input),struct('type','()','subs',{{1}}))

Daniel Shub
Daniel Shub 2012년 5월 18일
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
Jan
Jan 2012년 5월 18일
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

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


Ramuel Safarkoolan
Ramuel Safarkoolan 2021년 11월 17일
[a,~,~]=test(input);
will do the trick

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by