Function returning ans instead of three outputs

18 ビュー (過去 30 日間)
Sara Foster
Sara Foster 2019 年 9 月 8 日
回答済み: Povilas Simonis 2021 年 4 月 25 日
My function is:
function [R,G,B] = MostDistantPixel(pixels)
%rest of code
R = ipixel(1)
G = ipixel(2)
B = ipixel(3)
On the command window it says R = 50, G = 48, and B= 47.
However, it is not returning these outputs and returning only the first output R with a value of 50. How do I fix this?

採用された回答

Stephen23
Stephen23 2019 年 9 月 8 日
編集済み: Stephen23 2020 年 11 月 25 日
You need to call the function with three output arguments, e.g.:
inp = [...]; % your input array
[RR,GG,BB] = MostDistantPixel(inp)
Useful basic MATLAB concepts, such as how to call functions with multiple input/output arguments, are explained in the introductory tutorials:
Note that if a function that returns an output and it is called without any outputs being allocated to a variable, then its first output will be assigned to the default variable ans:
It is recommended to avoid referring to ans in code: it is recommended to always define your own output variables.
PS: You will probably also want to suppress the displaying of R, G, and B using semi-colons.
  7 件のコメント
Stephen23
Stephen23 2019 年 9 月 8 日
編集済み: Stephen23 2019 年 9 月 8 日
"So let’s say I use this function in another function, it will return the three outputs?"
Where you call it from makes absolutely no difference: if you define your function with three output arguments then when you call it you can allocate those three outputs to three variables. It makes no difference if you do this from the command line, inside another function, or in a script: the syntax is always the same (just like I showed in my answer).
Note that you can also call a function with fewer outputs than the function defines, the unassigned outputs are then essentially ignored (however in some cases, e.g. meshgrid, ndgrid, find, size, etc., the number of output arguments used can also change the functionality).
Sara Foster
Sara Foster 2019 年 9 月 8 日
Thank you! This has helped me a lot.

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

その他の回答 (1 件)

Povilas Simonis
Povilas Simonis 2021 年 4 月 25 日
I have similar problem, yet I dont manage to understand how to fix it..
function [Out] =test2(a)
if a>3
Out=a+1;
else
fprintf('Less than 4\n');
end
function gives me ans instead of Out

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by