Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Command Window text manipulation

December 28, 2011 7 Comments

Sometimes the most obscure problems have simple solutions.
A few days ago, a Matlab user asked whether it is possible to solve the flashing effect whenever he cleared the Command Window. It turns out that this user runs a long process, and wanted to display interim information (progress etc.) in the Command Window. The obvious solution that he employed was to display the data in the Command Window, and then erase the window (using clc) and rewrite the data periodically.

Using control characters

Now, there are obviously other ways of doing this, the most obvious being a dedicated GUI window that displays the information and updates periodically. But to solve the user’s immediate issue, the solution I provided (acting on the 80-20 Pareto principle – a dedicated GUI window is better but would take longer to set up) was to use control characters to erase old data when displaying new data, rather than clearing the window. Here is the basic pseudo-code that I suggested (slightly modified):

reverseStr = '';
for idx = 1 : someLargeNumber
   % Do some computation here...
   % Display the progress
   percentDone = 100 * idx / someLargeNumber;
   msg = sprintf('Percent done: %3.1f', percentDone)
   fprintf([reverseStr, msg]);
   reverseStr = repmat(sprintf('\b'), 1, length(msg));
end

reverseStr = ''; for idx = 1 : someLargeNumber % Do some computation here... % Display the progress percentDone = 100 * idx / someLargeNumber; msg = sprintf('Percent done: %3.1f', percentDone) fprintf([reverseStr, msg]); reverseStr = repmat(sprintf('\b'), 1, length(msg)); end

The idea is to use the backspace control-character (BS, or sprintf(‘\b’), or char(8)) repeatedly in order to erase the preceding characters from the Command Window, then print the new data.
(see related comments by Helge here)

Compatibility aspects

Back in the good-ol’-days, when I was hacking away c-shell scripts, ages ago when I created command-prompt C apps, and aeons ago on Vax (R.I.P.), I would have used the carriage-return control-char (CR, or sprintf(‘\r’), or char(13)) to completely erase everything up to the beginning of the current line. This would be much simpler than the repeated backspaces (using repmat in the pseudo-code above). Unfortunately, CRs behave differently in Matlab’s Command Window, causing \r to jump to the next line (similarly to \n), rather than erase to the beginning of the line. This is probably due to Java’s JTextArea’s implementation (on which the Command Window is based), and not due to Matlab itself. In any case, it shows that not all control characters behave the same way on different environments, which is actually not very surprising.
Another widely-used control character, the bell control-char (BEL, or sprintf(‘\g’), or char(7)) is not accepted at all by Matlab’s implementation of sprintf and its variants. Matlab users can always use the beep function of course, I’m just pointing this out as another inconsistency between Matlab’s *printf() implementation and that of other environments. And don’t even think of using raw device escape sequences (ah, the good-ol’-days, long gone now…).
Control characters that are accepted in Matlab and behave as expected include: FF (\f), NL (\n) and TAB (\t). These can be used in fprintf to modify the text spacing. The sprintf documentation mentions which of the control characters are accepted, so this is not, strictly speaking, an undocumented aspect. However, note that there is a discrepancy between the list of accepted control chars in the online/doc page compared to the help section (\a and \v are mentioned in the former but not in the latter).
For another type of Command Window text manipulation, namely colors, refer to my cprintf utility. For anyone who hasn’t noticed, I recently updated the utility on the Matlab File Exchange. Due to some internal modifications by MathWorks to the Command Window implementation in R2011b, cprintf no longer needs to pad color segments with spaces, and separate color segments can now be directly adjacent to each other (in R2011a and earlier, the spaces are unfortunately needed).
Have you used control characters in an innovative manner in your work? If so, please share your experience in a comment.
Happy New Year everyone!

Related posts:

  1. Another Command Window text color hack – Matlab's fprintf command has an undocumented hack to display orange-colored text. ...
  2. Bold color text in the Command Window – Matlab Command Window text can be formatted *bold* since R2011b. ...
  3. cprintf – display formatted color text in the Command Window – cprintf is a utility that utilized undocumented Matlab desktop functionalities to display color and underline-styled formatted text in the Command Window...
  4. Changing Matlab's Command Window colors – part 2 – The Matlab Command Window enables a limited degree of inline color customization - this post describes how to use it...
  5. Changing Matlab's Command Window colors – Matlab's Command Window foreground and background colors can be modified programmatically, using some of Matlab's undocumented internal Java classes. Here's how....
  6. EditorMacro v2 – setting Command Window key-bindings – The EditorMacro utility was extended to support built-in Matlab Editor and Command-Window actions and key-bindings. This post describes the changes and the implementation details....
Pure Matlab
Print Print
« Previous
Next »
7 Responses
  1. Donn Shull December 28, 2011 at 21:25 Reply

    The Vax certianly is a blast from the past! But I would guess that very few readers of this blog know what the related acronym DEC stood for or have experience entering a boot loader into a PDP8 via the toggle switches on the front panel.

  2. esp December 28, 2011 at 22:32 Reply

    See, for example, class “ConsoleProgressBar” http://www.mathworks.com/matlabcentral/fileexchange/30297-consoleprogressbar

  3. Helge December 29, 2011 at 13:29 Reply

    I used char(0) to clear the ‘CurrentCharacter’ property, checked IF 13==get(gcf,’currentcharacter’) … to detect whether the user has pressed the [RETURN] key, and did similar stuff also to check special keyboard input, e.g., TAB=char(9) or any left/right/up/downarrow char(28:31) etc. Not all of this is “innovative”, but clearing the ‘CurrentCharacter’ property is not as trivial as it seems… in fact, this property cannot be set to an empty value (R13-2007b):

    >> set(gcf,'currentcharacter','');
    ??? Error using ==> set
    Bad value for figure property: 'CurrentCharacter'.

    >> set(gcf,'currentcharacter',''); ??? Error using ==> set Bad value for figure property: 'CurrentCharacter'.

    The following, however, works:

    >> set(gcf,'currentcharacter',char(0));
    >> c=get(gcf,'currentcharacter')
    c =
         ''
    >> double(c )  %% really empty (not 0)? ... apparently, yes!
    ans =
         []

    >> set(gcf,'currentcharacter',char(0)); >> c=get(gcf,'currentcharacter') c = '' >> double(c ) %% really empty (not 0)? ... apparently, yes! ans = []

    Apparently, the ‘CurrentCharacter’ property can -in principle- be used to get/set virtually any char(0…255), incl. those for which no keys exist on the keyboard. However, I cannot exclude unexpected effects under different Matlab versions and OSs.

  4. Priya March 25, 2013 at 08:22 Reply

    Is it possible to display the result being displayed in a command window onto a static text box in GUI??

  5. JGit-Matlab integration | Undocumented Matlab July 10, 2013 at 11:02 Reply

    […] carriage return (or ‘r’) escape sequence which in Windows is the same as a newline (read here). So, I implemented a customized ProgressMonitor class for Matlab that uses backspace (or […]

  6. kasim December 12, 2013 at 11:06 Reply

    I use ‘dispstat’ function just for this purpose. It can update the previous output which is a missing function of default ‘disp’. Very simple to use. It can be downloaded from here:

    http://www.mathworks.com/matlabcentral/fileexchange/44673

    ***Sample usage:

    dispstat('','init'); % One time only initialization 
    dispstat(sprintf('Begining the process...'),'keepthis','timestamp'); 
    for i = 97:100 
        dispstat(sprintf('Progress %d%%',i),'timestamp'); 
        %doing some heavy stuff here 
    end 
    dispstat('Finished.','keepprev');

    dispstat('','init'); % One time only initialization dispstat(sprintf('Begining the process...'),'keepthis','timestamp'); for i = 97:100 dispstat(sprintf('Progress %d%%',i),'timestamp'); %doing some heavy stuff here end dispstat('Finished.','keepprev');

    ***Output:

    11:25:37 Begining the process... 
    11:25:37 Progress 100% 
    Finished.
    
    • Yair Altman December 12, 2013 at 11:30 Reply

      @Kasim – it would have been nice if you included a reference to this webpage in your utility’s description. After all, it’s based on the content of this webpage (specifically, the \b trick). It is not very polite to use someone’s work without acknowledging it; to then go back to that source and post a link to your work only increases the apparent impoliteness…

      The utility itself does indeed seem useful.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Nicholas (3 days 22 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Nicholas (3 days 22 hours ago): Hi Yair, Thanks for the reply. I am on Windows 10. I also forgot to mention that this all works wonderfully out of the editor. It only fails once compiled. So, yes, I have tried a...
  • Yair Altman (4 days 5 hours ago): Nicholas – yes, I used it in a compiled Windows app using R2022b (no update). You didn’t specify the Matlab code location that threw the error so I can’t help...
  • Nicholas (5 days 1 hour ago): Hi Yair, Have you attempted your displayWebPage utility (or the LightweightHelpPanel in general) within a compiled application? It appears to fail in apps derived from both R2022b...
  • João Neves (8 days 6 hours ago): I am on matlab 2021a, this still works: url = struct(struct(struct(struct(hF ig).Controller).PlatformHost). CEF).URL; but the html document is empty. Is there still a way to do...
  • Yair Altman (11 days 4 hours ago): Perhaps the class() function could assist you. Or maybe just wrap different access methods in a try-catch so that if one method fails you could access the data using another...
  • Jeroen Boschma (11 days 7 hours ago): Never mind, the new UI components have an HTML panel available. Works for me…
  • Alexandre (11 days 8 hours ago): Hi, Is there a way to test if data dictionnatry entry are signal, simulink parameters, variables … I need to access their value, but the access method depends on the data...
  • Nicholas (11 days 22 hours ago): In case anyone is looking for more info on the toolbar: I ran into some problems creating a toolbar with the lightweight panel. Previously, the Browser Panel had an addToolbar...
  • Jeroen Boschma (15 days 5 hours ago): I do not seem to get the scrollbars (horizontal…) working in Matlab 2020b. Snippets of init-code (all based on Yair’s snippets on this site) handles.text_explorer...
  • Yair Altman (43 days 7 hours ago): m_map is a mapping tool, not even created by MathWorks and not part of the basic Matlab system. I have no idea why you think that the customizations to the builtin bar function...
  • chengji chen (43 days 14 hours ago): Hi, I have tried the method, but it didn’t work. I plot figure by m_map toolbox, the xticklabel will add to the yticklabel at the left-down corner, so I want to move down...
  • Yair Altman (51 days 7 hours ago): @Alexander – this is correct. Matlab stopped including sqlite4java in R2021b (it was still included in 21a). You can download the open-source sqlite4java project from...
  • Alexander Eder (57 days 2 hours ago): Unfortunately Matlab stopped shipping sqlite4java starting with R2021(b?)
  • K (63 days 13 hours ago): Is there a way to programmatically manage which figure gets placed where? Let’s say I have 5 figures docked, and I split it into 2 x 1, I want to place 3 specific figures on the...
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top