GenerateMultiColorText
Version 1.0.0 (2.52 KB) by
Naveed Reza Aghamohammadi
Takes the hassle out of generating a multicolored text string for MATLAB text objects. Works with all standard MATAB text commands.
%GENERATEMULTICOLORTEXT Generates a multicolored text string for MATLAB text objects.
%
% chars = GenerateMultiColorText(textCell)
% chars = GenerateMultiColorText(textCell, colors)
%
% This function creates a concatenated text string where each segment is displayed
% in a different color. It is intended for use with MATLAB text objects that support
% the 'Interpreter' property set to 'tex'.
%
% INPUTS:
% textCell - Cell array of strings or character vectors. Each element is a text segment
% to be colored separately.
% Example: {'Hello', 'World', '!'} or {"Hello", "World", "!"}
%
% colors - (Optional) An N-by-3 matrix of RGB color values, where N is the number of text segments.
% Each row corresponds to the color of the respective text segment in 'textCell'.
% RGB values should be in the range [0, 1].
% If 'colors' is not provided or is empty, the function generates equidistant colors.
%
% OUTPUT:
% chars - A formatted string combining all text segments with their specified colors.
% This string can be used with text objects by setting 'Interpreter' to 'tex'.
%
% OPTIONS:
% The function requires the text object to have the 'Interpreter' property set to 'tex'.
% Ensure you specify this property when displaying the text.
%
% EXAMPLE:
% % Define text segments
% textCell = {'Hello, ', 'World', '!'};
%
% % Define colors for each segment (optional)
% colors = [1, 0, 0; % Red
% 0, 1, 0; % Green
% 0, 0, 1]; % Blue
%
% % Generate the multicolored text string
% chars = GenerateMultiColorText(textCell, colors);
%
% % Display the text in a figure
% figure;
% text(0.5, 0.5, chars, 'Interpreter', 'tex', 'FontSize', 14, 'HorizontalAlignment', 'center');
% axis off;
%
% SEE ALSO:
% text, annotation, sprintf
%
% NOTE:
% - The function assumes that 'textCell' is provided as a cell array of strings or character vectors.
% - The 'colors' matrix must have the same number of rows as the number of text segments.
% - RGB values in 'colors' should be between 0 and 1.
% - The function utilizes MATLAB's TeX interpreter for coloring text.
%
% AUTHOR:
% Naveed Reza Aghamohammadi, 11/19/2024
Cite As
Naveed Reza Aghamohammadi (2025). GenerateMultiColorText (https://uk.mathworks.com/matlabcentral/fileexchange/176043-generatemulticolortext), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2022b
Compatible with R2016a and later releases
Platform Compatibility
Windows macOS LinuxTags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.
| Version | Published | Release Notes | |
|---|---|---|---|
| 1.0.0 |
