Incompatible size error for display function
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
dpb
le 23 Fév 2025
Modifié(e) : dpb
le 23 Fév 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Spreadsheets dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!