MATLAB Answers

Elegantly refer to the second output from a function

조회 수: 310(최근 30일)
Xin
Xin 9 Feb 2018
Commented: James Tursa 9 Feb 2018
Hello everyone. I have a function (matlab function, say "ismember") and I want to use the second output from this function as index in a vector. For example:
data = rand(1,10);
[A,B] = ismember(1,[0,1,2,3,4,5]);
result = data(B);
My question is how do I skip the second line and directly use B in line 3.
Many thanks

  댓글 수: 0

로그인 to comment.

답변 수 (2)

James Tursa
James Tursa 9 Feb 2018
James Tursa 님이 편집함. 9 Feb 2018
Unless the function has an input argument syntax that specifies only returning B, you can't do this. You can throw away that A immediately with this syntax however:
[~,B] = ismember(1,[0,1,2,3,4,5]);
That won't prevent the function from calculating that 1st result, it is just thrown away immediately upon return so that it doesn't clutter your workspace.

  댓글 수: 2

Walter Roberson
Walter Roberson 9 Feb 2018
Right. Unfortunately there is no way in MATLAB to specify that you want to extract a particular output number of an expression and use that: you have to write the outputs to variables.
James Tursa
James Tursa 9 Feb 2018
It would be nice to have an "argout_wanted" that can be queried from within the function to find out which outputs the caller actually wants returned.

로그인 to comment.


Grigory Tagiltsev
Grigory Tagiltsev 9 Feb 2018
You have to call the function anyway. You can do [~,B] = ismember(1,[0,1,2,3,4,5]); and avoid A. It doesn't decrease a number of lines though. You can also cheat a bit and do [B,B] = ismember(1,[0,1,2,3,4,5]); in this case only the second output will be written to B.

  댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

태그


Translated by