Function changing the display?

조회 수: 19 (최근 30일)
Maria De Silva
Maria De Silva 2016년 4월 11일
답변: Steven Lord 2016년 4월 11일
if true
% code
function [ out ] = factorialeq( integer )
if( ~isinteger(integer) || integer < 0)
disp('error')
else
out=factorial(integer);
end
I want it to display and error message saying the input is non integer. Is that possible. Or since I'm using the isinteger the error message has already been set. Can I change it to display what I want it to say?

답변 (2개)

Guillaume
Guillaume 2016년 4월 11일
It's still not very clear what you want to do since the built-in factorial function that you're calling will carry out the check and display the error message for you.
Anyway, you can pass any string you want to display to the error function:
error('The input must be a non-negative integer');

Steven Lord
Steven Lord 2016년 4월 11일
There are two main issues with the code you wrote. The first is that the isinteger function doesn't do what you think it does. It does not check that its input contains integer values but that its input is of an integer type.
isinteger(5) % returns false
isinteger(int8(5)) % returns true
The second issue is that in the case where the input is invalid, you don't assign a value to the variable being returned as output. This will cause MATLAB to throw an error, but it won't be the one you expect or want. I recommend doing as Guillaume suggests and using error instead of disp.
But as Guillaume also pointed out, the factorial function included with MATLAB already does error for noninteger values. So if you wanted to throw a different error message, I would probably just use try and catch. Call factorial inside the try and if you reach the catch throw your own error. I'm not going to post the code since I suspect this is part of a homework assignment, but it's only going to be a couple lines long.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by