Incompatible size error for display function
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ben
el 23 de Feb. de 2025
Comentada: Walter Roberson
el 24 de Feb. de 2025
Hi everyone, I am currently beginning to learn MATLAB for university. I was playing around with it and I got this error:

This is my code:
%Calculating approximate maximum backhand range based off forehand range
f = input('What is your max forehand range in meters? ');
b = f + 5;
disp('You can throw a forehand about ' + f + ' meters which means you can throw a backhand about ' + b + " meters.")
What is the issue here and how do I fix it? Thank you in advance for your help
0 comentarios
Respuesta aceptada
dpb
el 23 de Feb. de 2025
Editada: dpb
el 23 de Feb. de 2025
f=10; b=f+5;
disp("You can throw a forehand about " + f + " meters which means you can throw a backhand about " + b + " meters.")
The "+" operator is only defined for strings, not char variables...
The char() string is an array of char so trying to add
msg1='You can throw a forehand about ';
whos msg1
msg1+f
whos ans
results in an array in which the value of f has been added to the value of the char() string -- which is an integer which matches the specific character in the ASCII table; internally they're still just numbers; it's only knowing to display as a char() variable that makes it look like text instead...
msg2='meters which means you can throw a backhand about ';
whos msg2
Now you see that msg1 and msg2 aren't the same length and therefore, can't be added. Of course, even if they just happened to have the same length having added 10 to the first message, it wouldn't be at all what was intended...
char(msg1+f)
The olden way of doing this before the strings class was introduced, one did the above with explicit formatting as
msg=sprintf('You can throw a forehand about %f meters which means you can throw a backhand about %f meters.',f,b);
disp(msg)
3 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!