MATLAB: How to manipulate text in uitable

cell formatformatMATLABuitable

Hello,
I have a uitable which is based on a cell.
Please see attached an example column.
I would like to do the following:
  1. Align ALL the fields to be in the CENTER.
  2. To make all the numbers in the following format: XXX.XXXEXX (I mean, no more than 3 digits after the dot).
Can someone post a simple code the the 2 tasks above? THANKS !!!

Best Answer

Three methods of centering data containing strings and numbers within a uitable column and setting the format of the numbers for Matlab releases
  1. >= r2019b
  2. >= r2016b
  3. >= r2013a
For Matlab r2019b or later
This will only work if the uitable is within a uifigure (not a regular figure) and requires Matlab r2019b or later.
It converts numeric values to string which often causes more work because if you need to access those values, you must convert them back to numeric.
% Create demo data


C = {'Normal';rand;rand;'Pass';rand;rand};
% Convert numbers to string in %3.2E format


isNum = cellfun(@isnumeric,C);
C(isNum) = compose('%3.2E ',[C{isNum}])
% Load data into UITable


fig = uifigure();
uit = uitable(fig, "Data", C);
% Center all values (requires r2019b or later & use of uifigure)
uis = uistyle('HorizontalAlignment', 'center');
addStyle(uit, uis, 'Column', 1)
For Matlab 2016b or later
This method uses regular figures and use pad() which wasn't available until 2016b.
It also converts numeric values to string which often causes more work because if you need to access those values, you must convert them back to numeric.
% Create demo data
C = {'Normal';rand;rand;'Pass';rand;rand};
% Convert numbers to string in %3.2E format
isNum = cellfun(@isnumeric,C(:,1));
C(isNum,1) = strsplit(strtrim(sprintf('%3.2E ',[C{isNum,1}])));
% Pad left and right with spaces to equate lengths
C(:,1) = pad(C,'both');
% Load data into UITable
fig = figure();
uit = uitable(fig, "Data", C);
For Matlab r2013a or later
Time to upgrade!
This version uses sprintf instead of compose and it uses a low-level method of padding instead of pad. It also uses strsplit which became available in r2013a.
It also converts numeric values to string which often causes more work because if you need to access those values, you must convert them back to numeric.
% Create demo data
C = {'Normal';rand;rand;'Pass';rand;rand};
% Convert numbers to string in %3.2E format
isNum = cellfun(@isnumeric,C(:,1));
C(isNum,1) = strsplit(strtrim(sprintf('%3.2E ',[C{isNum,1}])));
% produce pre and post pads
nchar = cellfun(@numel, C(:,1));
nSpaces = bsxfun(@minus, max(nchar), nchar)/2; % *
prePad = arrayfun(@(n){repmat(' ',1,n)},floor(nSpaces));
postPad = arrayfun(@(n){repmat(' ',1,n)},ceil(nSpaces));
% Pad the cell array
C(:,1) = strcat(prePad, C(:,1),postPad)
% Load data into UITable
fig = figure();
uit = uitable(fig, "Data", C);
*Thanks Walter Roberson for the bsxfun reminder!