0
0
MATLABdata~5 mins

String vs character array in MATLAB

Choose your learning style9 modes available
Introduction

Strings and character arrays both store text in MATLAB, but they work differently. Knowing the difference helps you choose the right one for your task.

When you want to store and manipulate text easily with built-in functions, use strings.
When you need to work with older MATLAB code that uses character arrays.
When you want to treat text as a sequence of characters, use character arrays.
When you want to combine or compare text data simply, strings are easier.
When you want to access or change individual characters, character arrays can be helpful.
Syntax
MATLAB
str = "Hello";  % String
charArray = ['H', 'e', 'l', 'l', 'o'];  % Character array

Strings are created with double quotes " ".

Character arrays use single quotes ' ' around each character or a single quoted sequence.

Examples
This creates a string and displays it.
MATLAB
str = "Hello, world!";
disp(str);
This creates a character array and displays it.
MATLAB
charArray = ['H', 'e', 'l', 'l', 'o'];
disp(charArray);
Shows empty string and empty character array.
MATLAB
emptyStr = "";
emptyCharArray = '';
disp(emptyStr);
disp(emptyCharArray);
Single character string vs single character array.
MATLAB
singleCharStr = "A";
singleCharArray = 'A';
disp(singleCharStr);
disp(singleCharArray);
Sample Program

This program shows how to create a string and a character array, access their first characters, and modify the second character in both.

MATLAB
str = "Hello";
charArray = ['H', 'e', 'l', 'l', 'o'];

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

% Access first character
fprintf('First character of string: %s\n', str(1));
fprintf('First character of char array: %s\n', charArray(1));

% Modify second character
str(2) = 'a';
charArray(2) = 'a';

fprintf('Modified string: %s\n', str);
fprintf('Modified char array: %s\n', charArray);
OutputSuccess
Important Notes

Strings are easier to work with for most text operations because MATLAB has many built-in string functions.

Character arrays are older and sometimes needed for compatibility with legacy code.

Strings use more memory but offer more features like string arrays and text processing.

Summary

Strings use double quotes and are modern, flexible text containers.

Character arrays use single quotes and treat text as a list of characters.

Choose strings for new code and character arrays for legacy or specific character-level tasks.