4.9 | 66 ratings Rate this file 215 Downloads (last 30 days) File Size: 15.7 KB File ID: #24093 Version: 1.10
image thumbnail

cprintf - display formatted colored text in the Command Window


Yair Altman (view profile)


12 May 2009 (Updated )

Displays sprintf-formatted strings in the Command Window using the specified color/underline style

| Watch this File

File Information

     count = cprintf(style,format,...)
CPRINTF processes the specified text using the exact same FORMAT arguments accepted by the built-in SPRINTF and FPRINTF functions.
CPRINTF then displays the text in the Command Window using the specified STYLE argument. The accepted styles are those used for Matlab's syntax highlighting (see: File / Preferences / Colors / M-file Syntax Highlighting Colors), and also user-defined colors.
The possible pre-defined STYLE names are:
   'Text' - default: black
   'Keywords' - default: blue
   'Comments' - default: green
   'Strings' - default: purple
   'UnterminatedStrings' - default: dark red
   'SystemCommands' - default: orange
   'Errors' - default: light red
   'Hyperlinks' - default: underlined blue
STYLE beginning with '-' o '_' will be underlined. For example:
   '-Blue' => underlined blue, like 'Hyperlinks'
   '_Comments' => underlined green
STYLE beginning with '*' will be bold (R2011b+ only). For example:
   '*Blue' is bold blue;
   '*Comments' is bold green etc.
Note: Matlab does not currently support both bold and underline, only one of them can be used in a single cprintf command. But of course bold and underline can be mixed by using separate commands.
STYLE also accepts a regular Matlab RGB vector, that can be negated for underlining. For example: -[0,1,1] means underlined cyan.
STYLE is case-insensitive and accepts unique (non-ambiguous) partial strings (for example, 'cy' instead of 'cyan').
Examples (see results in the attached screenshot):
   cprintf; % displays the demo
   cprintf('text', 'regular black text');
   cprintf('hyper', 'followed %s','by');
   cprintf('key', '%d colored', 4);
   cprintf('-comment','& underlined');
   cprintf('err', 'elements\n');
   cprintf('cyan', 'cyan');
   cprintf('_green', 'underlined green');
   cprintf(-[1,0,1], 'underlined magenta');
   cprintf('*blue', 'and *bold* (R2011b+ only)\n');
   cprintf([1,0.5,0],'and multi-\nline orange\n');
Bugs and suggestions:
Please send to Yair Altman (altmany at gmail dot com)
This code heavily relies on undocumented and unsupported Matlab functionality. It works on Matlab 7+, but use at your own risk!
A technical description of the implementation can be found at: http://UndocumentedMatlab.com/blog/cprintf
See details & current limitations in the main help section


This file inspired Google, English To Turkish Dictionary, Script Execution Notifier Using Pushover, Jsonrpc2: A Set Of Classes To Encode/Decode Json Rpc Messages, Tcprintf : Ansi Colored Output In Terminal, Set Prompt Set The Command Window Prompt, Ecopathlite.M: A Matlab Implementation Of Ecopath, and Lynx Matlab Toolbox.

Required Products MATLAB
MATLAB release MATLAB 7.5 (R2007b)
MATLAB Search Path
Other requirements Tested on Matlab 7.1 all the way up to 8.6 (R2015b), with a few version-specific quirks detailed in the help section.
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (89)
23 Jan 2016 Alex Poulsen

formats in error color

06 Dec 2015 Alexander Murphy

This is great

02 Nov 2015 Andres Melguizo Cortijo

Thanks!,very usefull!

26 Sep 2015 Alexander Vakulenko


21 Sep 2015 Ander Biguri

Thanks Yari, abusing Matlab again! While playing with it, I found out that single character formatting does not work in Matlab 2014b.



You might also want to look at the question in stackoverflow:


22 Aug 2015 Changchuan Yin

This is very useful function. Thanks!

I try to use it color character by character in a string, but it does not color a single character in a string. For example,

test = gene(1);
cprintf('cyan', test);

It does not color first the character 'A'. Could you please check? Would someone help me for this? Thank you!

08 Jul 2015 Joshua

Joshua (view profile)


03 Jun 2015 Mark Morehead

This is an excellent function that I use all of the time. It is very useful to have color coded text in the command window to make sure the users of the code are watching the most important information. It does have a few minor quirks (like all code does) but that does not take away from it being an excellent tool. The only way to improve this tool is if Mathworks were to take this on as their own function and integrate it so that it handles all the different platforms and upgrades successfully.

02 Jun 2015 Yair Altman

Yair Altman (view profile)

@retrobytes - of course it works, you have a bug in YOUR code (a missing '):

cprintf([1,0.5,0], 'text text %.0f text text %d text text\n', -pi, 5);

Sometimes, parts of the displayed text don't come out in the expected color, but the text is always displayed correctly. The invalid colors (when they happen) are due to internal Matlab implementation details over which we simply have no control. In most cases it works well, within those limitations.

Does this mean cprintf is a bad function? No - it simply means that it has some limitations. Within these limitations cprintf provides excellent functionality.

I'm sick and tired of people who do not appreciate the huge effort that went into creating this function, which nobody ever thought possible and nobody ever came even close to replicating. Criticizing it just because it is not 100% perfect in your eyes, although it gives you something much better than you had before is plain ingratitude. I guess that you would complain even if I gave you a brand new Mercedes car as a gift, if you thought its color was imperfect.

If you think that you can implement this function any better then go ahead and try it. Maybe then you'd appreciate all the hard work that went into creating cprintf.

Comment only
02 Jun 2015 retrobytes

A useful tool, overall.

Unfortunately, does not work (at least not correctly) with passing the variables at the end, e.g.:

cprintf(rgb('DarkOrange'), 'text text %.0f text text %d text text, var1, var2)

04 Mar 2015 Alessandro  
16 Feb 2015 Alessandro

Great job! Thanks a lot!

29 Jan 2015 Tony

Tony (view profile)

very nice. I use this function to display a matrix that the specific row needs to highlight with color red. very useful. wonderful work...

30 Dec 2014 Berks

Berks (view profile)

taking back a previous comment, this works just great on R2013a. Extremely useful, kudos.

30 Dec 2014 Berks

Berks (view profile)

I will be happy to hear from somebody who got it to work in newer matlabs - I Couldn't make it work on my R2013a (on mac).

Comment only
28 Nov 2014 Gareth Thomas  
06 Nov 2014 Oleg

Oleg (view profile)

11 Sep 2014 Thierry Dalon

1 issue found:
If I have a string containing an html link, on this line the text before the link is formatted in red. Very strange.
text='Titi <a href="matlab:disp(''toto'')">toto</a>'

Comment only
02 Jun 2014 Masoud

Masoud (view profile)

Thanks a lot!

14 Apr 2014 Simone Panza

Good job! However, I may have found a bug related to cell code mode.
Consider this piece of code

s1 = 'hello\n';
s2 = 'h\n';
cprintf('red', s1)
cprintf('black', s2)

if you run it as a normal script (using F5) everything is fine. But if you run the same code in cell mode (using CTRL+Enter) the result is not what you expected.
This is driving me crazy. I use Matlab R2013b and I use lots of cell code in my scripts, so this is giving me some annoyance.
This is even more complicated since if you try to run the code in debug mode, the problem doesn't show up anymore!
I think the problem is related to the fact that, when using cell code mode, the name of the script file is not passed to the command window (while it appears in the cmd window when using F5) and this in some way reflects in the computation of the current position in the command window.

23 Jan 2014 Christos Saragiotis

This is a really good submission, thanks!

I was able to add a predefined style 'Warnings' by
a. adding a 'Warnings' entry in the validStyles cell (after the 'Errors' entry) in function processStyleInfo,
b. changing the subsequent 'elseif mathces < 8' to 'elseif matches < 9' and
c. changing the following 'requestedColor = colors(matches-7,:);' to 'requestedColor = colors(matches-8,:);'.

It seems to be working fine so far.

10 Jan 2014 Stephen Cobeldick

An interesting exploration into the inner workings of MATLAB, beautifully explained by the author on his blog. I particularly like the innovative use of RGB values as the unique color strings, that allows any color to be displayed. (Great blog too!)

26 Dec 2013 Zoe

Zoe (view profile)

30 Oct 2013 Todd Karin  
04 Jul 2013 Dani Tormo

Good job! Thanks and congratulations!

26 Jun 2013 Dmitry

Dmitry (view profile)

24 May 2013 Martin Lechner

There is a minor bug with bold text. The last character of a bold text is displayed as normal text. This is only a problem if the bold text ends with no space or carriage return.
In the exampele below the 'd' of the bold text is shown in normal font.
cprintf('*key','bold'), cprintf('err','normal\n')

Nevertheless, a great tool!

23 May 2013 Nitin Singh  
23 May 2013 Martin Lechner  
27 Apr 2013 Barak Almog

Awesome submission. Works perfectly on my 2012b. Thanks alot, Yair!

13 Mar 2013 Yair Altman

Yair Altman (view profile)

Sébastien - you are using cprintf incorrectly. Firstly, the extra parameter 4 has no meaning since you are not using any printf fields (e.g. %d) in your string.

Secondly, you don't need (and actually should not use) \r - \r clears the current line to the beginning on some systems, which could explain what you are seeing.

Comment only
13 Mar 2013 Sébastien MAILFERT

Thanks for your code.
It works well with Matlab 2007 but colors are not displayed on my computer with Matlab 2012b.
The text is displayed but in white in fact.
If I write cprintf('k','test\r\n', 4), the line is written in white with a blue "-" before the string
If I write cprintf('-k','test\r\n', 4), text is displayed in blue and underscored with a blue "-" before the string.

Could you help me please?

28 Feb 2013 Karel Lebeda

Thanks a lot!
Anyway, I have one suggestion: it doesn't turn the colouring back off unless at the end of line, e.g.:
cprintf('r', 'aaa'); fprintf('bbb')
prints everything in red...

10 Nov 2012 Christopher Redwood

This is a fantastic submission. The bugs I have encountered pertain to R2011a. They are, as documented, a space is inserted at the front of each line, and that one must use \n at the end of each string in format. Minor inconveniences for such a good program. Great job Yair!

05 Nov 2012 Athena

Athena (view profile)

nice job! thanks.
i had problems using the function (R2012a) in a loop, colors did not work out nicely from iteration to iteration. i added fprintf('\n'); before the cprintf line and that seemed to solve, at least my problems. i also added ; to the end of all of my fprintf and cprintf lines.... that also helped.

12 Oct 2012 Grzegorz Kwiatek

Greate submission

12 Oct 2012 Grzegorz Kwiatek

Great submission.

07 Aug 2012 Yair Altman

Yair Altman (view profile)

@Adam - the version that I uploaded yesterday includes support for *bold* formatting

Comment only
07 Aug 2012 Patrice Tscherrig

Unfortunately on win7, R2011b 64bit

>> cprintf([255 175 0]./255, 'warning text')

does not produce the same colored text as on R2009a, WinXP, 32bit. Any idea why?

28 Jun 2012 Pio Nonus  
22 May 2012 Brian

Brian (view profile)

This is what makes Matlab fun! Thanks Yair

18 Apr 2012 Adam Wyatt

Adam Wyatt (view profile)


Suggestion - can you add support for bold text to. I presume its doable since the command window already utilizes bold text.

Comment only
14 Apr 2012 bedadipta

it is just aswm.... thank u ,thank u :)

12 Dec 2011 Martin Lechner  
28 Nov 2011 Yair Altman

Yair Altman (view profile)

For all the people who have noted about cprintf's issues with R2011b, the new version that was just uploaded fixes those problems, as well as the issue of the space (on R2011b only)

Comment only
23 Nov 2011 Rory Adams

You might find that changing the fprintf command on line 164 to use the standard output instead of standard error may solve your problem with the text colour

i.e. use
inplace of

Comment only
18 Nov 2011 Jerry Zhou  
19 Sep 2011 Szilárd Németh

A very useful function. Stopped working under R2011b (as Mark Morehead pointed it out).

Yair, do you plan to update it so that we can have this great stuff in future releases?

15 Sep 2011 Mark Morehead

I have been using the cprintf function and find it very useful.

I just installed Matlab V 2011b (64bit) and cprintf is no longer working properly.

When I run it, I get:
>> cprintf('text', 'regular black text');
_ t>>

If I highlight it, I get:
>> cprintf('text', 'regular black text');
regular black text>>

So the text is printing in white. There must be a color inversion problem caused by something in the update in Matlab.

06 Sep 2011 Jon C

Jon C (view profile)

30 Aug 2011 mohammad  
29 Aug 2011 daniloz

@Yair - I've found one bug:

Since I use black background and gray text for the command window, cprintf('text', 'Hello World!\n') was showing the string in black, i.e. invisible with my configurations.

By watching around a little bit, I figured out that the text color is "saved" in the 'ColorsText' preference, so I changed the code around line 242 to:

% Regular text
elseif matches == 1
style = 'ColorsText';

Noew, when I use 'text' as style, I get *exactly* the color I have set in the preferences.

17 Aug 2011 cK

cK (view profile)

12 Jul 2011 Henry

Henry (view profile)

This function is great. I've got only one problem. If I run it on a remote machine by ssh but without X (say via Cygwin), then it reports error:

<a href=""> </a>??? Attempt to reference field of non-structure array.

Error in ==> cprintf at 156
xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);

Obviously, I don't expect to see color when no display is specified. But I do want to my code platform independent. That is, if there is display, then show the colors. Otherwise, please just behave in the same way as fprintf(1, ...) (ie, please don't return error/failure).

Comment only
19 Jun 2011 Andrey Kan  
28 May 2011 Matthias  
27 May 2011 Paul Macey  
20 May 2011 Reza Farrahi Moghaddam  
17 May 2011 Ben

Ben (view profile)

This helps me a lot.

However, it cannot cooperate with fprintf.
When using

cprintf('Text', '3D distance error (max):');
cprintf('Keywords', '%f\n', max(EVert));

it produces

3D distance error (max): 0.226647

Since I do not want the leading space, when trying

fprintf('3D distance error (max):');
cprintf('Keywords', '%f\n', max(EVert));

it produced

3D distance error (max):_

There is underline with the right color, but the number is in WHITE.

Could you help me out, Yair?

Best regards,

12 Apr 2011 Cedric Wannaz

This function is great! It is in my todo list to use it, so I know almost nothing about it at this point. However, couldn't you replace the white space on line 145 with a \r for (at least partly) solving your white space issue?

fprintf('<a href="">\r</a>');

Just had a sneaky look, so I have no idea how it impacts the rest.

Best regards,


Comment only
05 Mar 2011 Yair Altman

Yair Altman (view profile)

@James - unfortunately, blinking text is difficult to implement.

If this is sufficiently important to you, I'll be willing to develop it for you for a fee - contact me by email if this is the case.

Comment only
05 Mar 2011 James Tursa

James Tursa (view profile)

Great work. Of course, that means I want more! Is it possible to have blinking text? I know this is generally obnoxious to use, but that is exactly what I want when I put up a warning message and a pause in a piece of code that is about to potentially crash MATLAB (a bug demonstration code).

16 Jan 2011 Evgeny Pr

Evgeny Pr (view profile)


CPRINTF in ~45 times more slowly than FPRINTF.
There is an opportunity to get rid of calling DRAWNOW in CPRINTF? This greatly reduces the performance.

Comment only
18 Dec 2010 Bijit Banik

Thanks a lot.

Comment only
18 Dec 2010 Yair Altman

Yair Altman (view profile)

Bijit - you cannot do that with cprintf, but you can do it via the text properties of the dialog box:

hDlg=helpdlg(Help_str,'Title and Authors');
hText = findall(hDlg,'type','text');
set(hText,'interpreter','tex','string','\color{red}Red text')

Comment only
18 Dec 2010 Bijit Banik

Is it possible to change the text color of a GUI dialog box text with this cprintf function? For example:

helpdlg(Help_str,'Title and Authors');

Now I want to see 'bijit, yair' in different color.

with thanks.

03 Nov 2010 Evgeny Pr

Evgeny Pr (view profile)

06 Aug 2010 Yair Altman

Yair Altman (view profile)

read the description: cprintf prints to the command prompt - NOT TO A FILE !

Comment only
29 Jun 2010 Zachary Danziger  
28 Jun 2010 Yair Altman

Yair Altman (view profile)

Sharron - I uploaded a new version that fixed the edge-case that you have reported

Comment only
25 Jun 2010 Sharron

This is a great tool!.
However I think the command doesn't work well in printing the back slash, for example

cprintf('Errors', '\\abc\n')

does not generate output \abc


Comment only
10 May 2010 André

André (view profile)

30 Jan 2010 Rob Campbell

Rob Campbell (view profile)

Nice! Although I run almost exclusively on Unix using the -nodesktop flag. Without the Mathworks command window this function doesn't work. In fact, it generates an error. Perhaps it ought to fail gracefully?

Comment only
02 Dec 2009 Rahul Prem Nazeer  
17 Nov 2009 Dmitry

Dmitry (view profile)

03 Nov 2009 A Millo

A Millo (view profile)

29 Sep 2009 LeFlaux

LeFlaux (view profile)

This is a great little tool! Thank You!

18 Jun 2009 Mike

Mike (view profile)

18 Jun 2009 Mike

Mike (view profile)

There seems to be another bug, this one involving the '%' character. For example,

cprintf( 'keyword', '%% keyword\n' )

merely turns the command prompt (double chevron) blue, rather than printing '% keyword' and a newline character.

fprintf( '%% keyword\n' ), on the other hand, prints just what you would expect.

Comment only
04 Jun 2009 Yair Altman

Yair Altman (view profile)

@Karl - this is a corollary of the known issue with non-newline-terminated strings. In this case, the initial fprintf() was non-newline-terminated, getting cprintf confused...

A workaround for this case is to simply use cprintf for the initial black text, instead of fprintf:

cprintf('text', 'Here: ');
cprintf('blue', 'Blue\n');

Comment only
04 Jun 2009 Karl

Karl (view profile)

This is great! I wish Matlab documented its Java innards better. Anyway, there seems to be another small bug.

fprintf('Here: ')
cprintf('blue', 'Blue\n');

results in a blue underscore followed by the word 'Blue' in white (invisible on white background of my command window - but shows up when highlighted).

However, the same code as above, only using '-blue' instead of 'blue', works fine (gives the expected underlined blue text).

I'm using Matlab 2007b on a Linux box.

03 Jun 2009 Alan B

Alan B (view profile)

27 May 2009 Yair Altman

Yair Altman (view profile)

yes Petter - this is a known limitation of CPRINTF that is mentioned in its help section as well as the TODO list (at the bottom of the file). Unfortunately, it seems that if there is no space separator, then Matlab attempts to combine the adjacent style segments, thereby overrunning the first segment's style with the second's. Adding a separator solves this. If anyone finds a workaround I'll be happy to hear. Until then it's a small price to pay...

Comment only
27 May 2009 Petter

Petter (view profile)

OK, I now think that may be required.

Comment only
27 May 2009 Petter

Petter (view profile)

The function prints an extra white space after each string. Example:

str = 'Welcome!';
n = length(str);
for k = 1:n
col = [k/n 0 0];

results in:
W e l c o m e !

Comment only
15 May 2009 Petter

Petter (view profile)

I did not know this was possible

14 May 2009 Aurelien Queffurust

Tested successfully with the current release R2009a under Windows and with R2008b under Linux 64-bits. Just a great submission!

13 May 2009 MATLABician

A while ago, a colleague asked me if it was possible to display in a color other than the default, in the Command Window, the values violating some thresholds in an optimization problem. My response was, "That must be doable, because MATLAB does that for, say, error messages. I will look into it." Well, you looked into it alright, Yair!

13 May 2009 Albert

Albert (view profile)

Great, thanks!

28 Sep 2009 1.1

Fixed some problems reported by Andreas G & Swagat K

28 Sep 2009 1.2

Fixed some problems reported by Andreas G, Swagat K

26 Jun 2010 1.3

Minor fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo

04 Mar 2011 1.4

Performance improvement

27 Nov 2011 1.5

Fixes for R2011b; fix by Danilo (FEX comment) for non-default text colors

06 Aug 2012 1.6

Fixes for R2012b; added bold style; accept RGB string (non-numeric) style

19 Oct 2012 1.7

Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes

20 Mar 2015 1.8

Fix: if command window isn't defined yet (startup) use standard fprintf, as suggested by John Marozas

20 Mar 2015 1.9

Fix: if command window isn't defined yet (startup) use standard fprintf, as suggested by John Marozas

23 Jun 2015 1.10

Fixed a few discoloration issues (some other issues still remain)

Contact us