cant get my function to give two outputs

20 次查看(过去 30 天)
I have this function I created (new to Matlab so it's basic).
function [y, z] = multi(a, b) y = mod(a + b,1); z = mod(a + 2*b,1);
but when I run the code it only give one output any tell me what's wrong.
thanks

回答(2 个)

Naty Shemer
Naty Shemer 2017-2-8
amm.. I am guessing you are running the function from the Command window? try calling the function instead of:
multi(a,b)
call it:
[y,z]=multi(a,b)
Matlab only returns the first value by default...
  1 个评论
Apple
Apple 2017-2-8
tried running from the command window and editor it produces the answer with ans = rather than y or z =

请先登录,再进行评论。


Steven Lord
Steven Lord 2017-2-8
From your description that includes ans, you called your multi function like this:
multi(a, b)
The names of the variables inside your function workspace that are returned as outputs from your function are completely independent of the names of the variables to which those outputs are assigned. With your multi function, I could if I wanted call it like this:
[apple, banana] = multi(a, b)
In this example, the data stored in the variable y inside multi, because y is listed as the first output in the function declaration line of multi:
function [y, z] = multi(a, b)
is assigned to the variable whose name appears first in the call to multi, apple. Similarly, the data stored in the variable z inside multi gets assigned to banana.
If you call the function with fewer outputs than it has declared it returns, any outputs past the last one with which it is called don't get assigned to anything. The one exception is ans.
The developer of the code gets to choose the names they use in their code for their variables (there are a few limitations as stated in the documentation for the isvarname function, but IMO they are reasonable limitations.)
The user of the code doesn't need to agree with, know, or even care what names the developer chose to use internally; they can use whatever names (again, subject to those same limitations) they want in their code.

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by