How do I Convert Cells containing Binary Values into Cells of Decimal Values and Decimal Values into Strings?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
William Collants
il 2 Giu 2020
Commentato: William Collants
il 4 Giu 2020
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 Commenti
Risposta accettata
Image Analyst
il 2 Giu 2020
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 Commenti
Image Analyst
il 4 Giu 2020
Modificato: Image Analyst
il 4 Giu 2020
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Types in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!