Error when debugging problem

1 view (last 30 days)
Zaakir  Essop
Zaakir Essop on 14 Mar 2016
Commented: Stephen23 on 14 Mar 2016
Hi I have to debug the following code but I keep getting errors which i do not know how to fix.Any help will be greatfull :
clear
clc
Letters = {'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'W' 'X' 'Y' 'Z'};
ValueToConvert = input('Please enter the value you wish to express as a number: ');
ValueString = num2str(ValueToConvert);
Base = input('Please specify the base in which you wish to represent the value: ');
Remainders = [];
while ValueToConvert > 0
Value = 0;
while ValueToConvert >= Base
Value = Value + 1;
ValueToConvert = ValueToConvert - Base;
end
Remainders = [ValueToConvert Remainders];
Value = ValueToConvert;
clear Value Remainders
end
Number = '';
for count = 1:1:size(Remainders,2)
if Remainders(count) <= 10
Number = [Number Num2Str(Remainders(count))];
else
Number = [Number Letters(Remainders(count) - 9)];
end
end
disp(['The value ' ValueString ' is expressed by the number ' Number ' in the base-' Base ' number system.'])
Im getting the following error:
Please enter the value you wish to express as a number: 766
Please specify the base in which you wish to represent the value: 16
* _error: 'Remainders' undefined near line 18 column 31
error: called from
Tutorial6Broken at line 18 column 13_*
Thanks

Accepted Answer

Stephen23
Stephen23 on 14 Mar 2016
Edited: Stephen23 on 14 Mar 2016
For no obvious reason you clear some variables using this line:
clear Value Remainders
and then expect to be able to refer to those variables again. Thus the error.
Once you clear a variable it does not exist. If it does not exist how do you expect to be able to refer to it on this line?:
Remainders = [ValueToConvert Remainders];
Although beginners love using clear everywhere it usually serves no purpose at all, and in your case just broke your code. Avoid sticking clear everywhere. This is cargo-cult programming.
  3 Comments
Stephen23
Stephen23 on 14 Mar 2016
Obviously your condition is never met, so the loop never finishes. Try displaying the value of ValueToConvert at the end of each while loop. Check out the values and decide why it does not meet the conditions for ending the loop.
You should also learn to use the debugging tools.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!