# is there any reason for this?

7 visualizaciones (últimos 30 días)
G A el 21 de Abr. de 2024
Comentada: G A el 21 de Abr. de 2024
In Matlab
"1" + "1" = "11"
but
'1' + '1' = 98
i.e.
char(49) = '1'
but
char(49) + char(49) = 98
Is there any reason for this convention?
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Respuesta aceptada

John D'Errico el 21 de Abr. de 2024
Editada: John D'Errico el 21 de Abr. de 2024
Is there any reason? Well, does there absolutely need to be a "reason"? These are a set of choices, made over a period of multiple decades, by different people, surely different groups of people.
First, operations with a charcter vector. They go back to the dawn of MATLAB.
'1' is a character vector, as is '11'. Arithmetic operations on it, like addition, or subtraction, first convert the elements to their ascii equivalents.
C = '1'
C = '1'
+C
ans = 49
That is, a '1' is ascii 49. So if you add them, you get 98. That seems clear.
C + C
ans = 98
Strings came out only fairly recently, as a better way of working with characters.
S = "1"
S = "1"
whos C S
Name Size Bytes Class Attributes C 1x1 2 char S 1x1 166 string
But here, they decided that it does not make sense to add two strings, and get a number out, converting to ascii. Far more sensible is to use the plus operator here as a concatenation operator.
S + S
ans = "11"
This works very nicely in some cases. I very much like it. For example...
X = 17;
% what I might have done in the past:
disp(['The year is: ',num2str(year(now)),', The variable X has value ', num2str(X)])
The year is: 2024, The variable X has value 17
% Using strings
disp("The year is: " + year(now) + ", The variable X has value " + X)
The year is: 2024, The variable X has value 17
The strings and the plus operator make things simpler. Easier to write, read, and debug.
But, you might ask, then why did they not just change how character vectors work? You should realize there are millions of lines of old MATLAB code out there. Some of them use character vectors in many different ways. Rather than forcing many thousands of people to modify their code, they just introduced a different class.
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
G A el 21 de Abr. de 2024
Thanks! It must be some reason of course and you explained it in your answer. And the reason of my question was my curiosity.

Iniciar sesión para comentar.

### Categorías

Más información sobre Logical en Help Center y File Exchange.

R2024a

### Community Treasure Hunt

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

Start Hunting!

Translated by