MATLAB: How to flush right to content of the cell array in MATLAB (R2013a)

alignmentflushrightMATLAB

I have a cell array with mixed data types that I would like to have flushed right. That is, I want my cell entries to be right-aligned.

Best Answer

Say you have a cell array defined as follows:
c = {'123';'Hello World!';'0.98765'};
Then , to have it right-aligned, you could create a function 'flushRight' defined by:
function output = flushRight(data)
% DATA is a cell array
[m,n] = size(data);
dataLengths = cellfun(@length,data,'UniformOutput',false);
maxLength = max(cell2mat(dataLengths));
output = cell(m,n);
for j = 1 : n
output(:,j) = cellfun(@(s) sprintf('%*s',maxLength(j),s),...
data(:,j),'UniformOutput',false);
end
end