Clear Filters
Clear Filters

cant get my function to give two outputs

7 views (last 30 days)
Apple
Apple on 8 Feb 2017
Answered: Steven Lord on 8 Feb 2017
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

Answers (2)

Naty Shemer
Naty Shemer on 8 Feb 2017
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 Comment
Apple
Apple on 8 Feb 2017
tried running from the command window and editor it produces the answer with ans = rather than y or z =

Sign in to comment.


Steven Lord
Steven Lord on 8 Feb 2017
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.

Categories

Find more on Entering Commands in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!