How to output optional variables in a function?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
Hi, I have a function where i want to either output a, b OR c given my input condition which is found in num.
I am getting an error. Output argument "b" (and maybe others) not assigned during call.
Can you please suggest a solution!
For example,
if num=2, i want to output a=10, b=5 and if num=4, i want to output c=100
function [a,b,c] = trial_function(num)
if num==2
a=10;
b=5
else if num==4
c=100;
end
end
채택된 답변
Walter Roberson
2015년 6월 15일
Whenever the user specifies a certain number of output variables on the left-hand side of an assignment, your routine needs to assign to at least that many variables starting from the left of the list.
So if the user only specifies 1 output such as if they called
v1 = trial_function(3)
then you would have to assign to at least the one variable in the left of your list, "a", and you could also assign to any of the other variables. It would, for example, be fine if you assigned to "a" and "c" but not "b" in this case; everything after the first one ("a") will be ignored.
If the user specifies two outputs, such as
[v1, v2] = trial_function(3)
then you need to assign to the first two outputs, "a" and "b", and you could also assign to any of the other variables; whatever you assign or do not assign to c will be ignored if the user only specifies two outputs. It would be an error to assign to "b" but not to "a" if the user requests two outputs.
If the user specifies
[v1, v2, v3] = trial_function(4)
then you would need to assign to all three outputs, "a", "b", and "c". The outputs v1, v2 would be given whatever value you assigned to "a" and "b": even if the user doesn't care what the values are, you must provide a value.
Please note that outside of your function, the outputs are considered only by position, not by name. If you were to do
c = trial_function(4)
then this would not match the "c" on the left side against the "c" of your output variable list: it goes strictly by position, so the outside "c" variable would be assigned the value of the variable in the first position of your list, what you call "a".
댓글 수: 6
I am still confused. The thing is that the number of outputs of the function can vary and I do not know beforehand which value should i output, whether a and b or c only depending on the num value. Can you please give an example based on the above case?
Thanks Yashvin
You can't do that. If the user specified
[v1, v2, v3] = trial_function(4)
then you cannot leave your "a" and "b" unassigned and only assign to your "c".
What effect would you be looking for if it could be done? In
[v1, v2, v3] = trial_function(4)
would you be wanting v1 and v2 to be left unchanged from what they were and only v3 be changed? What if v1 and v2 had no value before the call: would you be wanting them to continue to not exist?
The below code shows an example of checking how many outputs were requested and making different decisions based upon the number of outputs. It starts by assigning some value to each requested output variable; NaN or inf or any other value could have been used, as long as some value is certain to be assigned to each output that is used. Then the code might or might not change the default value.
function [a,b,c] = trial_function(num)
if nargout > 0
a = [];
end
if nargout > 1
b = [];
end
if nargout > 2
c = [];
end
if num==2
a=10;
b=5;
else if num==4
c=100;
end
end
If you want to get a bit more complicated, the below code does its work and then checks afterwards to see if any of the required output positions were not assigned values, assigning a default value if necessary. I do not recommend using this post-checking method as the structure does not allow you to return early from the routine, requiring you to always go all the way to the end.
function [a,b,c] = trial_function(num)
if num==2
a=10;
b=5;
else if num==4
c=100;
end
end
if nargout > 0 & ~exist('a','var')
a = [];
end
if nargout > 1 & ~exist('b','var')
b = [];
end
if nargout > 2 & ~exist('c','var')
c = [];
end
Thanks for your extensive explanation! Yea, option 1 is the best choice. Infact, even if i declare the variables as a=[],b=[],c=[], it will be fine. The function will output eventually an empty variable. I wanted to prevent the function from outputting am empty variable! However,I think this do it. I will ignore the empty variable afterwards.
Hi Walter,
I have a UDF defined as such:
function [len,blob_Center,blob_Area,top_height,bottom_height,blobSolidity,boundary] = thresholdmainblob(view,backgroundview,realscale,mm_to_clean,x)
It's fed with view of an image. Depending on the view it's fed, a boundary won't always be assigned
The "heights" are not assigned when the boundary is assigned. When that is the case, I assign [] to them.
What is strange is that when I call the function of a view that I don't care about the boundary, and thus boundary is not assigned, I still get the error:
Output argument "boundary" (and maybe others) not assigned during call to "thresholdmainblob".
While the call to function is in this format (I don't put boundary in the call):
[len,blob_Center,blob_Area,top_height,bottom_height,blobSolidity] = thresholdmainblob(view,backgroundview,realscale,mm_to_clean,x)
I did Ctrl+F through the code and the only place the output variable boundary is even mentioned is inside a conditional block that only triggers if the view where I care about boundary is called.
For now, I worked around the error by assigned a blank value to boundary at all times unless the conditional triggers, but I was just curious if you would have any ideas as to why this may be happening despite the position of the output not being before an output that is assigned
My thought would be that your condition does not do exactly what you think it does. But it is difficult to say without the code and data to test with.
PBM
2020년 5월 29일
It's a pretty long code so I did not post more than that here----- I will read through it again and see if I can pick it out
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
