How can I make strings in a cell equal size

9 views (last 30 days)
I'm trying to rigth aling a uitable data with my own format, I'm using my own format because none of the column's format help me (bank nor any), I have a data set I first format with java. This is how I call the function, I'm not using GUIDE because I think it generates a LOT of garbage code and I like to keep things simple:
MyTableFunc(MyData);
Inside the uitable gui func I have this:
MyTable = uitable;
for i = 1:numel(MyData);
DataSet{i} = char(java.text.DecimalFormat('#,###0.00').format(MyData));
end
FormattedData = cellfun(@(x) sprintf('%10d',x),DataSet,'un',0);
The problem: Not every string has the same size, as the numbers ranges from a couple characters to five or six characters, so when I do:
set(MyTable,'Data')
The numbers (represented in string) are not right aling. I want to right aling them in the uitable (using spaces in front of the formatted string), so when the %10d comes every string remains different, I'd like some way to automatically change it, something like (if I want the string to have 12 characters each):
TotalChar = 12-cellfun('length', DataSet);
FormattedData = cellfun(@(x) sprintf('%' TotalChar 'd',x),DataSet,'un',0);
How could I achive this?
[EDITED, Jan, code formatted]

Accepted Answer

Walter Roberson
Walter Roberson on 18 Jan 2013
Your current code has
FormattedData = cellfun(@(x) sprintf('%10d',x),DataSet,'un',0);
That format does produce a total of 10 characters for each element (that is representable in 10 characters); the format does put in leading blanks.
However, the piece you appear to be missing is that by default uitable uses a proportional spaced font, in which space are narrower than digits. You cannot really fix that by adding more spaces, as the extra spaces will also be narrower than digits. The cure for this all is to tell the table to use a fixed-width font.
  1 Comment
Marcos
Marcos on 19 Jan 2013
Thank you Walter, you were right, but I did changed the code just a bit, now I have:
FormattedData = cellfun(@(x) sprintf('%10s',x),DataSet,'un',0);
I don't know why the %10d were causing problems when I did the fixed-width font thing in the uitable, but with %10s everything looks just fine, I now have a perfectly right align numbers with commas and percentage symbols.

Sign in to comment.

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!