Ken & Mike on the MATLAB Desktop
June 29th, 2009
What does your MATLAB Desktop look like? (again)
Way back in May of 2007, we asked you what your MATLAB Desktops’ looked like. Well, we want to ask you again, but this time Mike and I would also like to ask why your desktop is the way it is. Also, this time we’re offering up free t-shirts to the first 3 thoughtful respondents.
Mike and I will gather up all the screen shots and explanations you send in, and then post a blog with all that good info next week.
Here’s what we’d like to know from you, which you can email to us at desktop_blog_feedback@mathworks.com:
- Your name as you’d like it to appear in the blog post (feel free to leave this blank).
- What version of MATLAB you’re using?
- A screen shot of your MATLAB Desktop (PNG preferred). Feel free to include multiple shots, and no need to scale them dow — we’ll take care of that.
- A paragraph or two about why you’ve setup your desktop the way it is.
- What your favorite feature of the actual desktop itself is (e.g. docking, tiling)?
Here are Mike and my responses:
Mike Katz, using 7.8 (R009a)
I destroy my preferences directory on a regular basis so I often keep coming back to the default layout introduced in R2008b. I’ve been keeping my editor docked in the middle since we first introduced that capability. I change the division of editor/command window depending if I’m in code writing or debugging mode. I often use the Command history for rerunning code, especially from previous sessions.
I like the shortcuts. Normally I keep about 12 items on there that set up certain projects or provide utility like formatting a string in the clipboard for pasting into this blog…
Ken Orr, using 7.8 (R009a)
The Editor is usually the focus of my work, so it gets the most space on the upper right of my desktop. I usually have a number of files open, so I’ve moved the tabs over to the right hand side, which lets them run vertically. I usually leave the workspace browser closed, as I don’t need it when writing MATLAB code. Also, I don’t use the Command History, so I leave that closed too.
I like being able to move my tabs around the Editor.
By
Ken Orr
Ken is a developer on the MATLAB Desktop team. He loves the art of graphic design as well as developing visually pleasing user interfaces - he's one of those 'crazy' Mac guys!
11:18 UTC |
Posted in Desktop |
Permalink |
13 Comments »
June 22nd, 2009
Interactive web pages in MATLAB, part 4
A few weeks ago Ashwin commented on my Interactive web pages in MATLAB series from last year asking about computing data in MATLAB and putting back into a web page. I didn’t take the time back then how to explain it because it’s not the most straightforward and requires a bit of javascript.
So without further ado, I’m going to demonstrate one way to take data round-trip from a web page through MATLAB (all running in the same MATLAB session). The main piece of this method is that I am going to have a start function which dynamically creates a web page which loads the desired workspace data. This dynamic page then loads a static page, which is the GUI the user interacts with. This page calls a callback function which evaluates the data from the page and starts the cycle over again. Here is the data flow.
The main function
The purpose of the main function is to be the entry point to the web GUI. It takes data passed in and puts it into a dynamically created web page, that loads our static page. This process could be simplified by creating the whole html part dynamically, but that looses the benefit of using a better html-editing tool to create a nice looking web page (this is not an example of that).
The tricky part is that we are storing our value to be used in the main GUI in a meta tag. This allows us to look it up from a javascript method in the main page. The main page is loaded in a frame so that it still has access to the meta tag created here. Otherwise we would have to write that meta tag directly to the main page.
function matlabfromjs4(value)
%matlabfromjs4 load a web gui to print out the result of the magic command
if nargin == 0
%if no arguments (i.e. the first time) then do not load any data
meta = ”;
else
%otherwise put it in a meta tag
meta = value;
end
meta = sprintf(‘<meta id=”valueToPutInPage” content=”%s”>’, meta);
%dynamically generate the html and write it out a temporary file
file = tempname;
fid = fopen(file,‘w+’);
fprintf(fid,[‘<html>\n\t<head>\n’…
‘\t\t<title>Calling MATLAB from JavaScript 4</title>\n’…
‘\t%s\n’…
‘\t</head>\n’…
‘\t\t<frameset>\n’…
‘\t\t\t<frame name = “main” src=”%s”>\n’…
‘\t\t</frameset>\n’…
‘</html>’],meta,[‘file:///’ which(‘matlabfromjs4.html’)]);
%matlabjs4.html is the main web gui
fclose(fid);
%load the page
web([‘file:///’ file], ‘-noaddressbox’);
The GUI page
When loaded in the web browser, this page sets the meta content and loads the matlabfromjs4.html into the browser. This page onload queries the value of that tag and writes it into a special div. This page also has a form element that when a value is typed in the box, it will ask MATLAB to do a computation based on that value (in this case magic) and what will refresh the page.
<html>
<head>
<script lang=“text/javascript”>
function calculatemagic() {
var magicValue = document.getElementById(”magic”).value;
document.location=”matlab:js4helper(”+ magicValue +”);”;
}
function loadvalues() {
var pval = parent.document.getElementById(”valueToPutInPage”);
return pval.content;
}
</script>
</head>
<body>
Enter a value for:
<tt><b>magic</b></tt> <input id=“magic” onblur=“calculatemagic()”>
<div id=“answer” style=“background:lightgray;font-family:Courier;”>
<script lang=“text/javascript”>document.write(loadvalues());</script></div>
</body>
</html>
The calculateMagic javascript function uses the previously described matlab: operator to call our helper function js4helper.
js4helper
The helper function calculates the output of the magic function and formats the output is a displayable in html string, and calls our main function again with the string, regenerating the frame page, starting the whole process over.
function js4helper(value)
%js4helper takes the value from the webpage, find the answer and formats it
if ~exist(‘value’,‘var’)
%need to check that no valid input was given in case input box was blank.
magicVal = ”;
else
val = magic(value);
[r,c] = size(val);
format = [repmat(‘%i ‘,1,r) ‘<br>’];
magicVal = sprintf(format, val);
end
matlabfromjs4(magicVal);
That’s the basics of creating dynamic html GUIs in MATLAB. For extra credit I’m leaving you with two assignments:
1. Use base64 encoding to add an image to the web page without having to create an image file.
2. Use ActiveX on Windows to hook a web page running in IE up to a MATLAB session.
UPDATE: (6/23/09) Download the files here: matlabfromjs4.zip
By
Michael Katz
Mike is a developer on the MATLAB Desktop team. When not describing himself in the third person, biking, homebrewing, or rooting for the home team, he's busy trying to make the world a better place for programming.
13:54 UTC |
Posted in MATLAB GUI |
Permalink |
2 Comments »
June 15th, 2009
Fold whatever you want using cells
Juliette recently suggested that users should be able to fold whatever code they like. While this is a great feature idea, the MATLAB Editor doesn’t currently support folding arbitrary sections of code. You can, however, simulate the feature using cells.
Start by turing on Cell folding in Preferences -> Editor/Debugger -> Code Folding (folding cells is off by default). Now, take your raw code, which we’ll say looks like this:
and insert cell markers before and after the code you want to fold, like this:
Finally, collapse the cell and voila! You’ve folded an arbitrary chunk of code!
I realize this isn’t the ideal solution for folding a random chunk of code, but it’s a reasonable workaround in the meantime.
By
Ken Orr
Ken is a developer on the MATLAB Desktop team. He loves the art of graphic design as well as developing visually pleasing user interfaces - he's one of those 'crazy' Mac guys!
11:24 UTC |
Posted in Editor |
Permalink |
4 Comments »
June 8th, 2009
Using the cell mode toolbar
The MATLAB Editor is great because supports many different workflows and user styles. Even though I call myself an advanced MATLAB user, I have long since stopped being surprised when I find out about something that has been there forever and is quite blatant in the UI. There are just some things that I don’t need to use in my normal work, but may be quite useful to others. One such thing is the cell mode toolbar. If the toolbar is not already present in the editor, you can activate it from the menu: Cell -> Enable Cell Mode.
The first two items on the toolbar are the ones I use a lot. They are evaluate current cell (Ctrl+Enter) and evaluate cell and advance to next (Ctrl+Shift+Enter). This is great for live demos, where you can put a single concept (of multiple commands) in a cell and then step through a file one cell at a time. The demo workflow also fits nicely with publishing, where each step of the demo publishes into a separate section. Just remember that evaluating a cell evaluates the enclosed commands in the base workspace, which is not necessarily the same workspace as if the file were run regularly.
The next two sections of the toolbar have a textbox surrounded by either a “+,-” or a “x,%”. It’s not obvious what to do with these. If you place the caret in the editor next to a number or select a number, then the +,-,x,% buttons will light up. Pressing them will increment/decrement or multiply/divide the selected number by the amount in the box and reevaluate the current cell. This is good for tweaking a numerical parameter, such as a coefficient, tolerance, or number of iterations/interpolations. In this example I’m tweaking the peaks input, which produces a nice visual change on each increment.
The next two buttons %% are a little more obvious but their icons are subtly different. The first one has a plus “+” in the icon and clicking it inserts a new cell marker. It’s handy to have that for the mouse, but I find it faster to type “%%”. The second one provides you a dropdown list of the cells in your file, the same way the function dropdown provides a list of functions in the file.
And remember, you can always customize the buttons that show up on the cell mode toolbar: File -> Preferences -> Toolbars -> Editor Cell Mode.
By
Michael Katz
Mike is a developer on the MATLAB Desktop team. When not describing himself in the third person, biking, homebrewing, or rooting for the home team, he's busy trying to make the world a better place for programming.
13:12 UTC |
Posted in Editor, Preferences, Publish |
Permalink |
4 Comments »
June 1st, 2009
Changing the error color for visibility
We understand that colors in the editor can cause difficulty for some users or with certain display devices. Each release we try to make the MATLAB UI more friendly in this area. For MATLAB R2009a, we rolled in some minor enhancements in this area with the new M-Lint display. For example, you can set the color of an error underline from the color preferences: File -> Preferences -> Colors -> Errors.
This preference changes not only the color of error strings in the Command Window, but also the color of the error underline in the editor and the stripe in the M-Lint panel.
In addition to a configurable color, there are new severity icons associated with each m-lint message. For error messages, the icon is a red circle with a white x, and for warnings it is a yellow triangle with an exclamation point. This improves the usability by providing a shape as well as color to identify the severity of the message. Those of you who tried out the pre-release version of R2009a will notice the icons changed from colored dots for this reason.
By
Michael Katz
Mike is a developer on the MATLAB Desktop team. When not describing himself in the third person, biking, homebrewing, or rooting for the home team, he's busy trying to make the world a better place for programming.
16:54 UTC |
Posted in Editor, M-Lint, Preferences |
Permalink |
No Comments »
May 25th, 2009
Colorizing text output
There have been a number of requests recently asking that we support colorized output in the Command Window (here, here and here). I won’t be offering a way to colorize the Command Window content, but I will be offering an alternative way to generate colorized output for viewing in a web browser.
Some of the users I’ve talked with want to color their output in the Command Window so that they can easily pick out print-outs that indicate a problem. Imagine you had a long running program that printed various “good” diagnostics, but also occasionally printed out a message indicating that something wasn’t quite right and needed to be looked at. It would be nice to color that text in red, or some other attention grabbing color. This is the case we’ll address below.
We’ll start by writing a simple function that takes a string and wraps it in an HTML font tag. This function will also take a color, which will be used for the font tags color attribute. Because the result will be HTML , the color value can be anything supported by font’s color attribute (e.g. red, #cccccc etc.). Here’s what that function looks like:
function colorizedstring = colorizestring(color, stringtocolorize)
%colorizestring wraps the given string in html that colors that text.
colorizedstring = [‘<font color=”‘, color, ‘”>’, stringtocolorize, ‘</font>’];
end
Now all we need to do is use the function. Start by creating an HTML file in which to put your output text. Then, run your function and write to the output file as necessary using the colorizestring function. Finally, close the file for writing and open it using the web command.
Here’s what a sample usage might look like:
%% Open an HTML file to write the output into.
filename = ‘colorizedoutput.html’;
fid = fopen(filename, ‘wt’);
%% Do the long running calculation that generates lots of output.
for i=1:100
outputswitch = rand;
if rand < 0.80
fprintf(fid, colorizestring(‘black’, ‘Everything is fine.<br/>’));
elseif rand < 0.90
fprintf(fid, colorizestring(‘orange’, ‘There may be a problem.<br/>’));
else
fprintf(fid, colorizestring(‘red’, ‘There is a problem.<br/>’));
end
fprintf(fid, ’some string<br/>’);
end
%% Close the HTML output file.
fclose(fid);
%% Open the HTML output file in MATLAB’s web browser.
web(filename);
and the resulting output:
This won’t solve everyone’s problems, but it should help to fill the gap until we can fully support colorized output in the Command Window.
By
Ken Orr
Ken is a developer on the MATLAB Desktop team. He loves the art of graphic design as well as developing visually pleasing user interfaces - he's one of those 'crazy' Mac guys!
17:06 UTC |
Posted in Command Window, Editor |
Permalink |
3 Comments »
May 18th, 2009
M-Lint across a project
Oftentimes I find myself working not just on one MATLAB file, but a whole project-full of multiple files. When I’m in a multi-file mode, I like to know how my code is doing and how much cleanup work I still have to do to get the files into a stable, presentable state. The M-Lint code checker built in to the Editor is a great tool for analyzing and fixing a single file, but not practical when you have a bunch of files.
Why open a series of files consecutively and tab between them just to find the outstanding messages when you can use the M-Lint report to see them all at once?
The report lets you see all the unresolved warnings and errors in all your files at once. This provides a quick way to gauge the health of your project.
There are two ways to get to the M-Lint report. First is through the Current Directory Browser:
The other is through the mlintrpt command. By default The M-Lint report uses your active M-Lint configuration, but you can use this command to specify an alternative configuration. See our previous post about M-Lint configurations for more details.
Let us know how M-Lint has helped or hindered your project-wide workflows.
By
Michael Katz
Mike is a developer on the MATLAB Desktop team. When not describing himself in the third person, biking, homebrewing, or rooting for the home team, he's busy trying to make the world a better place for programming.
14:33 UTC |
Posted in Current Directory, M-Lint |
Permalink |
3 Comments »
May 11th, 2009
Keep your code readable with smart indenting
The MATLAB Editor automatically indents your code for you as you enter it (if your haven’t turned the preference off). We call this smart indenting, and it makes reading code easier. Logical blocks like if/end and while/end have their content visually demarcated with white space, which helps you see the block of code as a single entity.
You do have some control over exactly how the Editor smart indents, but I think there is one option that results in more readable code. Here are the three options (my favorite is at the end):
Classic
In Classic mode, the function keyword does not cause indenting, so a lot of code is stuck against the left margin. I find this to indenting style to be the hardest to read because it’s hard to visually match an end to it’s start.
Indent nested functions
This mode is slightly better than Classic, in that nested functions are fully indented — I could deal with this mode if I had to.
Indent all functions
This mode indents everything, including the content of top level functions, and is therefore my favorite indenting mode. I find the code to be more readable as it better matches it’s logical structure. I’m sure my preference is heavily influenced by my experience with Java.
If you want to play around with the various smart indenting options, go to Preferences -> Editor/Debugger -> Language, select MATLAB as the language, and then change the value in the Function indenting format combo box.
What indenting style do you prefer?
By
Ken Orr
Ken is a developer on the MATLAB Desktop team. He loves the art of graphic design as well as developing visually pleasing user interfaces - he's one of those 'crazy' Mac guys!
18:07 UTC |
Posted in Editor |
Permalink |
16 Comments »
May 4th, 2009
Internationalization of GUIs
Recently, Mario asked on the MATLAB newsgroup about how to provide a localized version of his GUI made in GUIDE. This is an interesting problem with no official, but many worthwhile solutions.
Right now depending on where you live you can purchase MATLAB either in English or Japanese:
The translated strings that ship with MATLAB come compiled and bundled up, and we’re not able to extend our translation mechanisms into a tool that would be useable for MATLAB customers. This means we have to think of other ways for providing localizeable GUIs. Here’s an example GUI that I quickly whipped up using a few easily translateable nouns. I apologize ahead of time, the buttons will only work if you have the image processing toolbox as I took some of my favorite images from its demos. However, the language changing menu works without any toolboxes. There’s a lot more code than you’re used to seeing on this blog, so I’ve provided a zip file with all the examples at the end.

Below I present four of many possible strategies to create an internationalizeable MATLAB GUI. For each of these strategies the actual GUI code (the translateDemo.fig and translateDemo.m files) remain unchanged. The difference happens in the dispatch function getLabel.m, which is called from the following function by the menu callbacks. Note that menu labels have a different property to set than the uicontrols. I’ll leave it as an exercise for you to simplify this function using the UserData or Tag properties.
function setLanguage(lang)
% find the label or string for each of the uicontrols for a given language
% and set it.
h = guidata(gcf);
set(h.language, ‘Label’, getLabel(lang, ‘language’));
set(h.english, ‘Label’, getLabel(lang, ‘english’));
set(h.french, ‘Label’, getLabel(lang, ‘french’));
set(h.german, ‘Label’, getLabel(lang, ‘german’));
set(h.peppers, ‘String’, getLabel(lang, ‘peppers’));
set(h.children, ‘String’, getLabel(lang, ‘children’));
set(h.canoe, ‘String’, getLabel(lang, ‘canoe’));
Using MATLAB classes
The first method makes use of constant properties in MATLAB class objects, allowing us to define the strings using the same pattern as one class file per language. Note that the keys for all of the languages are in English. It doesn’t matter what the keys actually are, as long as they are consistent. As you can see from my getLabel function, I’m taking advantage of the default subsref to access a class property dynamically. I think it’s a neat trick.
getLabel.m
function xlatedString = getLabel(lang, label)
xlatedString = ‘???’;
switch lang
case ‘en’
xlatedString = EnglishStrings.(label);
case ‘de’
xlatedString = GermanStrings.(label);
case ‘fr’
xlatedString = FrenchStrings.(label);
end
The following is my class with the English labels. The French and German ones follow the same pattern.
EnglishStrings.m
classdef EnglishStrings
properties (Constant)
language = ‘Language’;
english = ‘English’;
french = ‘French’;
german = ‘German’;
canoe = ‘Canoe’;
children = ‘Children’;
peppers = ‘Peppers’;
end
end
The advantage of this method is that it takes the MATLAB search path out of the equation. If you can run the GUI code, you can get to the class objects–the file locations do not need to be hard coded.
Using XML
Hard coding the strings in class files may be a little a clunky or not fit into your workflow. The next method makes use of XML files, but you can use whatever combination of files and I/O methods to read them you’d like: plain text files (with fread), Microsoft Excel files (with xlsread), or even using a containers.Map and saving/loading .MAT files!
getLabel.m
function xlatedString = getLabel(lang, label)
xlatedString = ‘???’;
switch lang
case ‘en’
xmlfile = ‘english.xml’;
case ‘de’
xmlfile = ‘german.xml’;
case ‘fr’
xmlfile = ‘french.xml’;
end
try
xDoc = xmlread(xmlfile);
root = xDoc.getDocumentElement;
strings = root.getElementsByTagName(’string’);
for i=0:strings.getLength - 1
if strcmp(strings.item(i).getAttribute(‘id’), label)
%translate from java string to MATLAB string
xlatedString = char(strings.item(i).getTextContent);
end
end
catch %#ok<CTCH>
%ignore any read errors and use ‘???’
end
french.xml
<?xml version="1.0" encoding="UTF-8"?>
<strings>
<string id="language">Langue</string>
<string id="english">Anglais</string>
<string id="french">Français</string>
<string id="german">Allemand</string>
<string id="canoe">Canoë</string>
<string id="children">Enfants</string>
<string id="peppers">Poivrons</string>
</strings>
Using a Java Resource Bundle
Java provides a built-in mechanism for storing strings and choosing them based upon locale called a ResourceBundle. We can take advantage of java.util classes from MATLAB so this method uses Java’s solution for our MATLAB GUI. Remember to convert the java.lang.String returned from the bundle using the MATLAB char function.
getLabel.m
function xlatedString = getLabel(lang, label)
%using the java resource bundle
xlatedString = ‘???’;
try
file = java.io.File([’strings_’ lang ‘.properties’]);
inputStream = java.io.FileInputStream(file);
resourceBundle = java.util.PropertyResourceBundle(inputStream);
xlatedString = char(resourceBundle.getString(label));
catch %#ok<CTCH>
%ignore any read errors and use ‘???’
end
strings_de.properties
language=Sprache
english=Englisch
french=Französisch
german=Deutsch
canoe=Kanu
children=Kinder
peppers=Paprikas
The Java ResourceBundle mechanism comes with the ability to automatically select the right file based upon the locale information and filename. To take advantage of that, we’d have to discuss how MATLAB and the ClassLoader interact…a topic for a different post.
Google Translation Services
Thanks to smart people at Google, you can get live translation to/from nearly any language. For this version of the GUI, I’ve added Spanish, Finnish, Filipino, and Turkish to the menu for almost no extra work. All the strings are translated live through Google’s translation API. I won’t interpret their Terms of Service for you, but if you do decide to use their services, play nice: it’s a great service they’re giving away for free.
getLabel.m
function xlatedString = getLabel(lang, label)
xlatedString = ‘???’;
try
url = ‘http://ajax.googleapis.com/ajax/services/language/translate’;
%’en’ (English) is the base language
page = urlread(url,‘get’,{‘v’,‘1.0′,‘q’,label,‘langpair’,[‘en|’ lang]});
pattern = ‘(?<=”translatedText”:”)(.+?)(?=”)’;
xlatedString = regexp(page,pattern,‘match’,‘once’);
catch %#ok<CTCH>
%ignore any read errors and use ‘???’
end
To make this nicer, I should probably look up the stored English strings instead of using my object labels for the translation (i.e. this doesn’t work for a phrase and doesn’t do the correct capitalization). Also, this code can be cleaned up a little using François Glineur’s JSON Parser from the MATLAB file exchange.
The real power here, I think is that you can provide a localized UI without having to develop a competency in that language. Of course the real question is whether or not it is better to provide no translation or a translation that could be wrong and confusing.
Determining Language Automatically
Most modern operating systems know something about the user’s environment such as the location and language. Java is able to get this information from the system and thus you can get it from MATLAB:
java.util.Locale.getDefault().getLanguage()
This returns the cute little two-letter language code that is consistent with the ones I’ve been using, and so we can stick this in the openingFcn function and have out GUI automatically detect the language and choose the appropriate strings.
function translateDemo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to translateDemo (see VARARGIN)
% Choose default command line output for translateDemo
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
%default to the peppers
peppers_Callback(handles.peppers, [], handles);
setLanguage(char(java.util.Locale.getDefault().getLanguage()))
A web search should reveal how to change the language settings for your particular OS. Here’s how to do it for Windows XP, and the result of making my machine think I understand Finnish:
I’d like to close this post asking my high school teachers, colleagues in France and Germany, and Aurélien to forgive me for any embarrasing translation mistakes. Bon Chance!
You can download the demo code right-clicking here and doing a Save As. I will also put them on the MATLAB file exchange and link them once they are up.
By
Michael Katz
Mike is a developer on the MATLAB Desktop team. When not describing himself in the third person, biking, homebrewing, or rooting for the home team, he's busy trying to make the world a better place for programming.
13:02 UTC |
Posted in MATLAB Central, MATLAB GUI |
Permalink |
2 Comments »
April 27th, 2009
New figure capture methods for publish
In R2009a, we added two new figure capture methods to publish. The figure capture method determines the way in which publish grabs screen shots of your figures, in order to insert it into the final published document.
Here are descriptions of the new figure capture methods, along with exactly what they capture:
entireGUIWindow (the new default):
This figure capture method grabs the content of your figure window. For a plot, this will be the axis. For a GUIDE figure, this will include the title bar (note that the getFrame method would not include the title bar on the GUIDE figure). This will be the option you want to use most of the time.
entireFigureWindow
This figure capture method grabs the entire figure window (including the window chrome, e.g. the title bar) for all types of MATLAB figures. Use this option with prudence, as including the window chrome will detract from the content of your figure. This option is most appropriate if your creating a tutorial where you want to make it obvious that the graphic is a MATLAB figure.
To see descriptions and visuals of all the figure capture methods, check out the doc.
By
Ken Orr
Ken is a developer on the MATLAB Desktop team. He loves the art of graphic design as well as developing visually pleasing user interfaces - he's one of those 'crazy' Mac guys!
15:07 UTC |
Posted in Configuration Editor, Publish |
Permalink |
No Comments »
|
Recent Comments