How can I check for semicolon termination of my own function
2 次查看(过去 30 天)
显示 更早的评论
My function does something and then writes information to the screen by using
function a = say_hi(b)
a = b;
fprintf(1, 'Hello World');
end
I would like to check if the line in the script that called this function was terminated by a semicolon, such that merely does a = b in that case. Is that possible?
Kind regards,
Jan
1 个评论
Doug Hull
2011-3-21
OP said in answers instead of comments:
---
Thanks Walter,
I understand what you say. Let me rephrase the question. I could do what I want by defining the function as follows:
function a = say_hi(b, print)
a = b;
if (print == 1)
fprintf(1, 'Hello World');
end
end
But then I would have an additional input parameter, which is undesired. I am looking for a keyword such as 'nargin' that is available inside the function space to check for its termination i.e. '\n' or ';\n'.
采纳的回答
Walter Roberson
2011-3-21
Semi-colon does not suppress anything explicitly printed: it only affects whether the value of assignments are automatically printed.
4 个评论
Walter Roberson
2011-3-22
With eval, I could construct a clause that had a semi-colon if and only if the test said that there was no semi-colon. Remember Matlab is interpreted and what is to be executed can be constructed on the fly.
更多回答(1 个)
Jan
2011-3-22
1 个评论
Walter Roberson
2011-3-22
Your first function can possibly be rewritten as:
function a = say_hi(b)
if nargout
a = b;
else
fprintf(1, 'Hello World');
end
In your second function, you should use strcmpi(param, 'DisplayOn') and for the value, instead of looking for the string 'true', you should look for non-zero values, to be consistent with how parameters are defined for the Matlab libraries.
I believe there are utility routines that can do the parameter parsing for you; you can find examples in nearly any of the Mathworks-provided routines.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!