From not very in-depth research there seems to be no way to color strings being output to the terminal in Matlab when using the disp
command. Luckily there is fprintf
and the idea that things will work just as in the ordinary terminal when you want to color strings or make them bold. I wrote two functions for doing this. The first one prints the colored string to the terminal. The second returns a string with the appropriate modifications to make it print in color or bold using fprintf
. You can download them in a zip file here: colorstrings
function printc(str,color) % Prints a colored version of the string to the terminal in Matlab. It is easy to % add your own specified colors by adding the color name and its code to the arrays % below. % % PURPLE = '\033[95m'; % CYAN = '\033[96m'; % DARKCYAN = '\033[36m'; % BLUE = '\033[94m'; % GREEN = '\033[92m'; % YELLOW = '\033[93m'; % RED = '\033[91m'; % BOLD = '\033[1m'; % UNDERLINE = '\033[4m'; END = '\033[0m'; % If no color specified we bold by default if nargin < 2 coloredStr = strjoin({'\033[1m',str,END,'\n'},''); fprintf(coloredStr); return; end colorNames = {'PURPLE','CYAN','DARKCYAN','BLUE','GREEN','YELLOW','RED','BOLD','UNDERLINE'}; colorStrIdxs = [95,96,36,94,92,93,91,1,4]; for idx = 1:numel(colorNames) if strcmp(color,colorNames{idx}) coloredStr = strjoin({'\033[',num2str(colorStrIdxs(idx)),'m',str,END,'\n'},''); fprintf(coloredStr); return; end end % If no color matched we bold by default coloredStr = strjoin({'\033[1m',str,END,'\n'},''); fprintf(coloredStr); return; end |
and
function coloredStr = colorstr(str,color) % Returns a colored version of the string to the terminal in Matlab. It is easy to % add your own specified colors by adding the color name and its code to the arrays % below. % % OBS! String needs to be printed with fprintf to have the desired effect! % % PURPLE = '\033[95m'; % CYAN = '\033[96m'; % DARKCYAN = '\033[36m'; % BLUE = '\033[94m'; % GREEN = '\033[92m'; % YELLOW = '\033[93m'; % RED = '\033[91m'; % BOLD = '\033[1m'; % UNDERLINE = '\033[4m'; END = '\033[0m'; % If no color specified we bold by default if nargin < 2 coloredStr = strjoin({'\033[1m',str,END},''); return; end colorNames = {'PURPLE','CYAN','DARKCYAN','BLUE','GREEN','YELLOW','RED','BOLD','UNDERLINE'}; colorStrIdxs = [95,96,36,94,92,93,91,1,4]; for idx = 1:numel(colorNames) if strcmp(color,colorNames{idx}) coloredStr = strjoin({'\033[',num2str(colorStrIdxs(idx)),'m',str,END},''); return; end end % If no color matched we bold by default coloredStr = strjoin({'\033[1m',str,END},''); return; end |