can't get the real result for addition and division using basic arithmetic operations. pls help..

1 view (last 30 days)
I have 3 values
jum1 = num2str(length(B1))
jum2 = num2str(length(B2))
jum4 = num2str(sum(roundObjects))
run on command window (the real values) :
jum1 =
12
jum2 =
62
jum4 =
2
but when I adding for example
rasio = jum2+jum4
in command window
rasio =
104 100
and when I use another function like this
rasio = (jum1 / (jum2 + jum4))
in command window
rasio =
0.4850
I think all results of my function not show the real values as I wish. Is there anything wrong of my functions??
  2 Comments
John D'Errico
John D'Errico on 20 Nov 2013
Edited: John D'Errico on 20 Nov 2013
Is there a sane reason why you are converting everything to a string?????????? And then trying to perform arithmetic on strings????????

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 Nov 2013
num2str() does not create symbolic variables: it converts the numbers into strings of characters. The internal representation of the character '1' is not 1; the internal representation for the character '1' happens to be 49. When you do the addition, you are not adding 62 + 2, you are adding ['6' '2'] + '2' which is internally [54 50] + 50, which gives you the [104 100] that you see.
The characters '0' through '9' are internally 48 through 57. char(48) == '0'.
The reasons that the characters '0' through '9' are not represented internally as the decimal values 0 through 9 are historical, involving mechanical movements on "automatic telegraphs" and 5 bit codes with "shift select" characters as needed to move between ranges. Decisions taken like 100 years ago that got merged into standards that still carry through (because there is no good reason to change them.)

More Answers (1)

Roger Stafford
Roger Stafford on 20 Nov 2013
Edited: Roger Stafford on 20 Nov 2013
As John indicates, your trouble is trying to do matlab arithmetic with strings. When you apply an operation like + or / to character strings, matlab first converts them back to the corresponding array of their ASCII values, and then does the operation. Both your answers are correct when interpreted in this manner. The string '12' converts to the array [49,50], '62' to [54,50] and '2' to [50[, so the operations you have are:
jum2+jum4 = [54,50] + [50] = [104,100] which is true
and
jum1/(jum2 + jum4) = [49,50]/[104,100] = 0.4850 which is also true. (This latter is matrix division.)
The lesson to be learned here is: Don't convert your numbers to character strings and then expect to do ordinary arithmetic operations with them.

Community Treasure Hunt

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

Start Hunting!