What is the output of the following MATLAB code?
str1 = "Hello"; str2 = "World"; char1 = ['Hello']; char2 = ['World']; result1 = str1 + " " + str2; result2 = [char1 ' ' char2]; disp(result1) disp(result2)
Remember that strings use + for concatenation, while character arrays use square brackets [].
In MATLAB, strings (double quotes) concatenate with + operator, adding spaces if included. Character arrays concatenate by placing them inside square brackets []. Both produce the same visible output when displayed.
What will be the output of the following MATLAB code?
str = "MATLAB"; charArr = ['M' 'A' 'T' 'L' 'A' 'B']; lenStr = strlength(str); lenChar = length(charArr); disp(lenStr) disp(lenChar)
Check how strlength and length functions behave on strings and character arrays.
strlength returns the number of characters in a string. length returns the number of elements in an array. Both return 6 here.
What error does the following MATLAB code produce?
str = "Data"; charArr = ['S' 'c' 'i' 'e' 'n' 'c' 'e']; result = str + charArr;
Consider the types of variables and what + operator supports.
MATLAB does not allow + operator between a string and a character array. This causes an undefined operator error.
Consider the following MATLAB code:
str = "Hello"; charArr = ['H' 'e' 'l' 'l' 'o']; char1 = str(2); char2 = charArr(2);
What are the values of char1 and char2?
Remember that indexing a string returns a string scalar, indexing a character array returns a char.
Indexing a string returns a string scalar (still double quotes). Indexing a character array returns a single character (single quotes).
What is the output of this MATLAB code?
str = "Test"; charArr = ['T' 'e' 's' 't']; result = strcmp(str, charArr); disp(result)
Check if strcmp supports comparing string and character array.
strcmp converts string inputs to character arrays internally and compares them correctly, returning 1 for equality.