Three methods of centering data containing strings and numbers within a uitable column and setting the format of the numbers for Matlab releases
- >= r2019b
- >= r2016b
- >= 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.
C = {'Normal';rand;rand;'Pass';rand;rand};
isNum = cellfun(@isnumeric,C);
C(isNum) = compose('%3.2E ',[C{isNum}])
fig = uifigure();
uit = uitable(fig, "Data", C);
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.
C = {'Normal';rand;rand;'Pass';rand;rand};
isNum = cellfun(@isnumeric,C(:,1));
C(isNum,1) = strsplit(strtrim(sprintf('%3.2E ',[C{isNum,1}])));
C(:,1) = pad(C,'both');
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.
C = {'Normal';rand;rand;'Pass';rand;rand};
isNum = cellfun(@isnumeric,C(:,1));
C(isNum,1) = strsplit(strtrim(sprintf('%3.2E ',[C{isNum,1}])));
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));
C(:,1) = strcat(prePad, C(:,1),postPad)
fig = figure();
uit = uitable(fig, "Data", C);