for loop or str2num incorrectly adding 48 to results?

조회 수: 4 (최근 30일)
Kirston Barton
Kirston Barton 2017년 3월 23일
댓글: Kirston Barton 2017년 3월 24일
I have the following code (which was part of a homework assignment, but I have solved the problem), I just don't understand why between lines 10 and 11, this code is adding 48 to the gg when it inserts it into vector q? I solved it by subtracting 48 from gg on line 10, but this makes no sense to me (first of all why I have to do it and second of all why is allows me to subtract 48 when I have converted it to a string on line 8). Can someone please explain what is going on here. It is driving me crazy! I have tried on two computers with tons of different inputs, completely closed and reopened matlab, cleared all values...It keeps happening.
a='1234567890'; aa='1234567890'; function b=add(a,aa) k=0; for i=10:-1:1 f=str2num(a(i))+str2num(aa(i))+k; if f > 10 g = num2str(f); gg=g(2); q(i)=gg; k=str2num(g(1)); else q(i)=f; end end

채택된 답변

Michelangelo Ricciulli
Michelangelo Ricciulli 2017년 3월 24일
It is doing that because every character of the string '10', is memorized in matlab with an encoding. So '0' is actually stored as a 48 and for example '1' is stored as 49, 'a' is 97 , etc...
If you want the number represented in a character, you should use
q(i)=str2num(gg);
because this will convert the char to an integer.
  댓글 수: 1
Kirston Barton
Kirston Barton 2017년 3월 24일
This worked, thank you for pointing this out. Good thing to keep in mind for future functions!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2017년 3월 24일
편집: Jan 2017년 3월 24일
This is the effect of confusing the number 0 with the character '0'. When you add the character '0' to a number or append it to a numerical array, its ASCII value is used, and this is 48:
double('0')
x = 1
x = [x, '0']
The same happens for '1', which has the ASCII code 49.
You code contain several bugs:
  1. The output b is not created
  2. In the case f>10 you append a character to q(i), but in the other case you append the number f.
  3. Defined before the loop if q is a double of char vector. Otherwise this depends on the first assignment.
  4. What happens for f==10?
  댓글 수: 1
Kirston Barton
Kirston Barton 2017년 3월 24일
Hi Jan,
Thank you for looking at this so thoroughly. Like I said, it is a bit of homework, so I just cut this little loop out of the larger function so that I could see if the same problem repeated and so that I don't post my solution for other people. Don't worry, it all does fit into a larger story with all the variables populating and outputting somewhere. I really appreciate you taking a look and helping out with the primary question!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by