How do I Convert Cells containing Binary Values into Cells of Decimal Values and Decimal Values into Strings?
11 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Image Analyst
2020-6-2
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
3 个评论
Image Analyst
2020-6-4
编辑:Image Analyst
2020-6-4
If that's what you wanted, you would just simply instantiate numbers to nan's rather than the less direct way (more kludgy) of instantiating them to 9999 and then checking if all elements encountered prior to the current element are still 9999 and setting them to nan. And of course removing comments is almost never a good idea because they explain the code so that later when you look at it you'll understand what you did.
% Find out which columns have nan's so we can skip them.
columnsWithNan = any(isnan(A), 1);
numbers = nan(1, columns); % Preallocate output
% Now process getting decimal number for each column
for col = 1 : columns
if columnsWithNan(col)
continue; % Skip this element if it's a nan.
end
thisCol = sprintf('%d%d%d%d%d', A(:,col)); % Get binary string.
numbers(col) = bin2dec(thisCol); % Convert string to a number.
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!