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

1 visualización (últimos 30 días)
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 comentarios
John D'Errico
John D'Errico el 20 de Nov. de 2013
Editada: John D'Errico el 20 de Nov. de 2013
Is there a sane reason why you are converting everything to a string?????????? And then trying to perform arithmetic on strings????????
setiawandika
setiawandika el 20 de Nov. de 2013
Editada: setiawandika el 20 de Nov. de 2013
I guess I was wrong to use the num2str()function to perform arithmetic. thanks

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 20 de Nov. de 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.)

Más respuestas (1)

Roger Stafford
Roger Stafford el 20 de Nov. de 2013
Editada: Roger Stafford el 20 de Nov. de 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!

Translated by