0
0
MATLABdata~5 mins

Character arrays and strings in MATLAB

Choose your learning style9 modes available
Introduction

Character arrays and strings let you work with text in MATLAB. You can store, change, and display words or sentences.

You want to store a name or label in your program.
You need to join or split sentences.
You want to compare two pieces of text.
You want to display messages to the user.
You need to read or write text data from files.
Syntax
MATLAB
%% Character array syntax
charArray = ['H', 'e', 'l', 'l', 'o'];

%% String syntax
str = "Hello";

Character arrays use single quotes and are arrays of characters.

Strings use double quotes and are easier to work with for text operations.

Examples
This creates a character array and displays: MATLAB
MATLAB
charArray = ['M', 'A', 'T', 'L', 'A', 'B'];
disp(charArray);
This creates a string and displays: MATLAB
MATLAB
str = "MATLAB";
disp(str);
Shows empty character array and empty string.
MATLAB
emptyCharArray = [''];
disp(emptyCharArray);

emptyString = "";
disp(emptyString);
String with a newline character to show multiple lines.
MATLAB
multiLineString = "Line1\nLine2";
disp(multiLineString);
Sample Program

This program shows how to create and change character arrays and strings, then prints them.

MATLAB
% Create character array and string
charArray = ['H', 'e', 'l', 'l', 'o'];
str = "Hello";

% Display both
fprintf('Character array: %s\n', charArray);
fprintf('String: %s\n', str);

% Change a character in the character array
charArray(1) = 'J';
fprintf('Modified character array: %s\n', charArray);

% Change the string
str = "Jello";
fprintf('Modified string: %s\n', str);
OutputSuccess
Important Notes

Character arrays are older style; strings are newer and easier for text work.

Changing characters in strings requires creating a new string, unlike character arrays.

Use strings for most text tasks unless you need character-level control.

Summary

Character arrays use single quotes and are arrays of characters.

Strings use double quotes and are easier to work with for text.

You can create, display, and modify both in MATLAB.