How to convert cell array to float array?
28 次查看(过去 30 天)
显示 更早的评论
Hello! I have a cell array (1000x11) of binary digits like that:
0 1 0 0 0 0 1 0 0 0 0
0 1 0 1 1 1 0 1 1 1 0
1 1 1 0 0 1 0 1 1 1 0
0 0 1 1 1 1 1 0 1 1 0
0 0 0 1 0 0 0 0 1 1 1
0 0 0 0 0 1 0 0 0 1 1
...
Each 11 digit row represents a float number, where the last 10 digits are the numbers after the dot. How can I convert that cell array to an array (1000x1) of decimal floats for example :
0.528
0.750
1.814
0.502
0.135
0.035
...
0 个评论
回答(2 个)
Jan
2021-5-6
编辑:Jan
2021-5-6
% If the input is a cell containing the chars '0' and '1':
B = cell2mat(YourCell);
Value = B(:, 1) - '0' + bin2dec(B(:, 2:11)) / 1000;
[EDITED] and if the values are the doubles 0 and 1:
B = cell2mat(YourCell);
Value = B(:, 1) + (B(:, 2:11) * 2.^(9:-1:0).') / 1000;
By the way, this would be more efficient for the first case also:
B = cell2mat(YourCell) - '0';
Value = B(:, 1) + (B(:, 2:11) * 2.^(9:-1:0).') / 1000;
2 个评论
Jan
2021-5-6
Unfortunately you did not provide some input data, which I could download or use by copy&paste. Therefore my answer contained some guessing about the type of your inputs.
I'm adding a version for numerical values in the input cell, wait some minutes...
Stephen23
2021-5-6
编辑:Stephen23
2021-5-7
M = [... as a numeric matrix (e.g. CELL2MAT or STR2DOUBLE)
0 1 0 0 0 0 1 0 0 0 0
0 1 0 1 1 1 0 1 1 1 0
1 1 1 0 0 1 0 1 1 1 0
0 0 1 1 1 1 1 0 1 1 0
0 0 0 1 0 0 0 0 1 1 1
0 0 0 0 0 1 0 0 0 1 1];
V = pow2(9:-1:0)/1000;
D = M(:,1)+M(:,2:end)*V(:)
Or, depending on how those binary digits are specified:
V = pow2(0:-1:-10);
D = M*V(:)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!