can't get the real result for addition and division using basic arithmetic operations. pls help..
Show older comments
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
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????????
setiawandika
on 20 Nov 2013
Edited: setiawandika
on 20 Nov 2013
Accepted Answer
More Answers (1)
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.
1 Comment
setiawandika
on 20 Nov 2013
Categories
Find more on Common Operations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!