Incompatible size error for display function

1 view (last 30 days)
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

Accepted Answer

dpb
dpb on 23 Feb 2025
Edited: dpb on 23 Feb 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.")
You can throw a forehand about 10 meters which means you can throw a backhand about 15 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
Name Size Bytes Class Attributes msg1 1x31 62 char
msg1+f
ans = 1×31
99 121 127 42 109 107 120 42 126 114 124 121 129 42 107 42 112 121 124 111 114 107 120 110 42 107 108 121 127 126
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
whos ans
Name Size Bytes Class Attributes ans 1x31 248 double
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
Name Size Bytes Class Attributes msg2 1x50 100 char
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)
ans = 'cy□*mkx*~r|y□*k*py|orkxn*kly□~*'
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)
You can throw a forehand about 10.000000 meters which means you can throw a backhand about 15.000000 meters.
  3 Comments
Ben
Ben on 24 Feb 2025
Ah okay I see, so basically basically because the two pieces of text are different sizes vector-wise they can't be added together. The way you fix that is by creating strings, which will store the text in the same vector size no matter how many characters the text has.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!