How to change the matlab default ans?

This is what is want to get: Write a function called get_sign.m that takes a scalar double-precision value as its input and returns a string '1' or '0' depending on the input’s sign.
>> get_sign (10.25)
a n s = 0
>> get_sign ( -65)
a n s = 1
And here is my code:
function x = myfunction(x)
if x > 0;
disp('ans = 0');
else
disp('ans = 1');
end
end
I'd get
>> get_sign(20)
0
ans =
20
How to remove the ans = 20 and only displays ans = 0 or 1.

Réponses (2)

Walter Roberson
Walter Roberson le 27 Sep 2015
The requirements are contradictory. The text of the question requires that '0' or '1' be returned (not printed), but the examples require that 'a n s = 0' or 'a n s = 1' be printed and no value be returned. You cannot meet both requirements at the same time.
This is what it would look like if '1' was being returned:
>> '1'
ans =
1
Notice that 'ans' has no spaces inside it, and that the output is over several lines. This output form is automatic and not under the control of the function being called. If you need
a n s = 1
to be emitted then it has to be printed (displayed) and nothing can be returned.
You will need to resolve this contradiction before you can proceed.
Andrei Bobrov
Andrei Bobrov le 27 Sep 2015
get_sign = @(x)x < 0

1 commentaire

get_sign = @(x) char('0' + (x < 0))
but this does not satisfy the contradiction about 'a n s = 1' or 'a n s = 0' compared to returning '0' or '1'

Connectez-vous pour commenter.

Catégories

En savoir plus sur Files and Folders dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by