What does it mean when ~ is used as one of the outputs for a function?

4 ビュー (過去 30 日間)
darkgod89
darkgod89 2016 年 10 月 28 日
コメント済み: James Tursa 2016 年 10 月 28 日
I have seen a few scripts where ~ is used as one of the output variables for a function/command? What is this supposed to mean and how is it useful? For example, in one of the lines for the script for the function divergence.m, I find the line [px, ~] = gradient(u);

採用された回答

James Tursa
James Tursa 2016 年 10 月 28 日
編集済み: James Tursa 2016 年 10 月 28 日
It means that the particular output that would ordinarily be returned to a variable at that spot is instead discarded automatically. E.g.,
[px, ~] = gradient(u);
is essentially equivalent to:
[px, dummy] = gradient(u); clear dummy
  2 件のコメント
Guillaume
Guillaume 2016 年 10 月 28 日
Well, in this particular case, it means that whoever wrote the line don't really know what they're doing. There's no point ignoring later outputs of the function*, simply do not ask for them. The line is exactly the same as:
[px] = gradient(u).
The ~ is useful when you want to ignore earlier outputs of the function such as:
[~, py] = gradient(u); %don't care about x gradient, but need second output.
*: unless the behaviour of the function changes depending on the number of output. This is not the case for gradient but is for find. e.g.:
idx = find(matrix); %return linear indices
[r, ~] = find(matrix); %return rows, ignore columns
James Tursa
James Tursa 2016 年 10 月 28 日
All good points. I will add that the ~ does not prevent the function from actually calculating that particular output argument. It is in fact calculated (the function still thinks it needs to return two outputs) ... it is just automatically discarded per the syntax. So using ~ is more of a coding convenience rather than a resource or time saver. (Is there a way for the function to detect when the caller has used ~ for an output?)

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

その他の回答 (1 件)

LauraLee Austin
LauraLee Austin 2016 年 10 月 28 日
It indicates that you are not using that output variable.
[FX,FY] = gradient(F)
Let's say you wanted the FY variable but not FX:
[~,FY] = gradient(F)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by