필터 지우기
필터 지우기

cant get my function to give two outputs

조회 수: 7 (최근 30일)
Apple
Apple 2017년 2월 8일
답변: Steven Lord 2017년 2월 8일
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