MATLAB: How to Convert Cells containing Binary Values into Cells of Decimal Values and Decimal Values into Strings

binarycell arraycell arrayscellfunconditionconvertdecimaldi2deexeptionfunctionfunctionsmat2cellMATLAB

Hi Guys,
Let's say I've a Matrix A with 5 Rows and 1000 Columns, consisting mostly of 0s and 1s. Maybe every ~50th or ~100th Column or so contains a Number
other than 0 or 1. Their distribution seems to be totally random. They're infrequent, but they're there.
Here's the thing:
I'd like to convert those Columns of 0s and 1s from their 5 digit binary values into a decimal value. So,
A = mat2cell(A,size(A,1),ones(1,size(A,2))); %Convert A to Cell Array with each Column its own Cell
B = cellfun(bi2de(A')) %Convert the Content of each Cell from Binary to Decimal
would, I guess, do the trick, if it weren't for the monkey wrench thrown in there of those occasional Non-Binary Values.
Is there a function to tell Matlab to, if a cell contains only 0s and 1s, convert its content into Decimal,
but if it contains other integers, simply output "Unknown", yielding a Cell array with the same number of cells as the Input Array.
Kind regards,
Tim

Best Answer

Try this:
% Create sample data.
A = zeros(5, 1000);
A(randperm(numel(A), 200)) = nan;
A(randperm(numel(A), 800)) = 1;
[rows, columns] = size(A);
% Find out which columns have nan's so we can skip them.
columnsWithNan = any(isnan(A), 1);
numbers = zeros(1, columns); % Preallocate output
% Now process getting decimal number for each column
for col = 1 : columns
if columnsWithNan(col)
continue;
end
thisCol = sprintf('%d%d%d%d%d', A(:,col));
numbers(col) = bin2dec(thisCol);
end