MATLAB: How to create a binary to decimal/decimal to binary function file

binarybinary to decimalconvertdecimalfunction filehomework

hello,
I am a little new to writing matlab function files.
I need to write a function file that, takes in either a binary or decimal and converts it to either decimal or binary respectively. The program should first ask whether to convert to binary or decimal.
I know that matlab already has the dec2bin, bin2dec commands so how can i go about making a function file that will first ask what I am converting to and then proceed to make the proper conversion?
All comments, thoughts, ideas, pointers, and any thought provoking ideas will be greatly appreciated!
Thank You

Best Answer

You made several mistakes in your code, lets have a look through it. Firstly you define the function with
function output = cenversion(input)
But notice how you specify the input argument name input. This is immediately going to cause you problems, because this is also the name of the inbuilt input function, which you also want to use. You should never shadow inbuilt functions or variables like this: avoid naming any of your own variables or functions with the same names as inbuilt ones.
Then you try to check the user-selection with isa(input,'1'), but when you read the documentation for isa , this syntax is nowhere to be found. isa check for a particular class, and '1' is not a known class name, so this is never going to work.
Try this code instead:
function out = binXdec(val)
fprintf('Available options:\t 1 = decimal to binary \t 2 = binary to decimal\n')
switch input('Please select your option: ','s')
case '1'
out = dec2bin(val);
case '2'
out = bin2dec(val);
end
end
Note how I used the more robust syntax for input, with the second optional 's' argument, and did not shadow any inbuilt functions or variables, and used the simpler fprintf(...) rather than disp(sprintf(...)) When I save this and run it, I get this in my command window:
>> binXdec(123)
Available options: 1 = decimal to binary 2 = binary to decimal
Please select your option: 1
ans =
1111011