How Do I Prevent The First Value in the Output of a Function From Showing?
3 次查看(过去 30 天)
显示 更早的评论
When I run my code, despite having semicolons on each function, I am getting an answer dispayed to the command window. I have figured out that this answer displayed directly correlates with the first output in my function (I'm assuming the correct format is function [output] = example (input) ). I would really like to get this function to work without displaying any output. Please note that I have already tried placing a semicolon next to the function itself. Please try running this code yourself. It will make alot more sense! Thanks!
For this function I get an answer displayed in the command window that is equal to Ax:
function [ Ax, Ay, Bx, By, Cx, Cy ] = Input_Triangle_Points ()
Point_A = input ('Enter the the value for point A as a matrix: ');
disp('')
Point_B = input ('Enter the the value for point B as a matrix: ');
disp('')
Point_C = input ('Enter the the value for point C as a matrix: ');
disp('')
Ax = Point_A (1,1);
Ay = Point_A (1,2);
Bx = Point_B (1,1);
By = Point_B (1,2);
Cx = Point_C (1,1);
Cy = Point_C (1,2);
end
command window displays:
ans =
Ax (whatever Ax may be)
0 个评论
回答(1 个)
Walter Roberson
2023-10-23
When you call a function and you do not have a semi-colon at the end of the call, then MATLAB interprets that as a request to display the first output of the function if the function had at least one output.
The solution is to put a semi-colon at the end of the call.
However, it is possible to code a function to detect whether it was called in a context that requires an output. You can do that by testing nargout . If nargout is 0 then the function was called without an explicit or implicit output requirements. When you detect that nargout is 0, you can choose to not assign anything to the first output variable, or you can choose to clear that output variable. If the first output variable is undefined at time of return, in a context that does not require an output, then nothing will be displayed.
experiment_one()
experiment_one();
disp(experiment_one())
experiment_two()
experiment_two();
disp(experiment_two())
function out1 = experiment_one
disp('entered 1')
out1 = 123456;
end
function out1 = experiment_two
disp('entered 2')
out1 = 56789;
if nargout == 0; clear out1; end
end
2 个评论
Walter Roberson
2023-10-23
When you press the green Run button, that is equivalent to going down to the command line and calling the function with no parameters and with no explicit outputs.
If that is what you are doing and it is important that Ax not be displayed when the user does that, then you need to use the nargout test.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!