Why am I getting 387 as the sum of my vectors when I input 1x1x1?

1 次查看(过去 30 天)
i probaly dont understand how the str2num command wroks but sor some reason when i input 1x1x1, get matlab to remove the x's from it and convert whats left to a serires of numbers and than take the sum of those numbers i get 387. why is that? i know matlab reads a string 1 as 49 thats probably why im getting that answer. How would i get aorund it and get Matlab to read string 1 as the value 1? Thanks for the help.
numbers = input('Enter your numbers that you want the sum of serperated by x: ', 's')
erase(numbers, 'x')
str2num(numbers)
sum1 = sum(numbers,'all')
fprintf('the sum of your numbers is = %f', sum1)

采纳的回答

Guillaume
Guillaume 2019-12-4
编辑:Guillaume 2019-12-4
Your problem is not with str2num (although using str2num is not recommended, but that's another topic).
Your problem is more fundamental is that the only thing that
somefunc(whateverinput)
does is display the output(s) of the function to the command line and then immediately discards the output(s) since it's not stored in anything.
somevariable = somefunc(whateverinput);
on the other hand does store that output in somevariable.
In effect, your call to erase does nothing since you never store ther result of erasing 'x' and your call to str2num does nothing since you never store its output either. Therefore you're summing the character of your numbers variable which still contains your original input '1x1x1'.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by