suppressing output variables in matlab

2020-02-07 12:24发布

I am using a function with multiple outputs in Matlab, but am only interested in one of the outputs. I would like to suppress the other output variables (i.e. avoid them being returned and placed into memory). For example, with the max function:

[output1 output2] = max(matrixA, [], 1);
% output1 returns the maximum, which i'm not interested in
% output2 returns the index of the maximum, which i *am* interested in

Is there any way to call the function so that output1 is not returned? And if there is, does it offer any memory advantage over calculating as above but immediately calling clear output1 to remove output1 from the memory?

Thanks for your help.

2条回答
家丑人穷心不美
2楼-- · 2020-02-07 12:43

Use the tilde:

[~, output2] = max(matrixA, [], 1);

I doubt there would be much memory advantage (apart from clerical stuff like allocating output variables, etc.)) since the function will run completely and allocate all that it needs to. This way, you just don't get the value, and the value of the first output variable in the scope of the max function will be garbage-collected.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-07 12:53

Replace any output variables you don't want with a ~ character.

E.g.

[~,I] = max(matrix);

This pattern has an advantage over clear in that the MATLAB interpreter and just-in-time compiler can avoid the memory and CPU costs of calculating ignored variables.

Edit

Here is the documentation and a blog post by Loren Shure on this use of ~. I can't find any definite information about use of ignored variables for eliminating unnecessary computation.

查看更多
登录 后发表回答