New to matlab and I do not understand given code

2 views (last 30 days)
When IC is a seven digit number and I need to add the digits in the odd numbered position which ic variable x and I need to add the digits in the even numbered posititon which is variable y. The answer I was given states that when using the sum() i need to minus 48 from both and I do not understand why.
x = sum((ic(2:2:end)-48))
y = sum((ic(3:2:end)-48))

Accepted Answer

John D'Errico
John D'Errico on 4 Dec 2022
Edited: John D'Errico on 4 Dec 2022
As much as I dislike doing homework for students, this is a case where I will relent, because it is very uncear why one would subtract 48, and because you have a valid question about MATLAB.
You have a number in a CHARACTER FORM. Thus:
N = '1234567890'
N = '1234567890'
This is NOT stored as a number, but merely a character representation of that number. This is something that many students do not understand the difference. And it is sort of subtle in the eyes of some. Is a picture of something the same as that thing itself? But is a picture of a symbol not just the same symbol? We might start an interesting philsophical debate here. Anyway, MATLAB stores those digits in ascii form when you have such a chacter vector. In the ascii table, they start at element 48.
char(48:57)
ans = '0123456789'
Now, MATLAB allows one nice trick. You can actually subtract a number from a character string. Or you can even subtract two character strings. See how this works.
N - 48
ans = 1×10
1 2 3 4 5 6 7 8 9 0
Do you see this operation converts the character representation into a true number for each digit?
Personally, I like this next version better, since you don't need to remember where zero appears in the ascii table:
N - '0'
ans = 1×10
1 2 3 4 5 6 7 8 9 0
I think now you should see what that code is doing. It converts the characters into true numbers for each digit. Then it sums up the digits you want to sum.
  2 Comments
John D'Errico
John D'Errico on 4 Dec 2022
It is very worth remembering the trick of subtracting a sting from a string. For example, where is the letter 'A' stored in the ascii table? The monadic plus operator helps us there.
+'A'
ans = 65
And going the other way:
char(65)
ans = 'A'
And of course we can do this:
char('A' + (0:25))
ans = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
But this also works:
'a':'z'
ans = 'abcdefghijklmnopqrstuvwxyz'
char([84 104 101 115 101 32 97 114 101 32 97 108 108 32 103 111 111 100 32 116 114 105 99 107 115 32 116 111 32 114 101 109 101 109 98 101 114 46])
ans = 'These are all good tricks to remember.'

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!