Using multiple functions in cellfun
8 次查看(过去 30 天)
显示 更早的评论
I want to clean up a nasty for loop. Here is the loop I'm trying to remove.
for j=1:line_num
bin_str = dec2bin(hex2dec(HEX_DATA{j,1}));
OUT.1{j, 1} = bin2dec(bin_str(1:(end-11)));
OUT.2{j, 1} = bin2dec(bin_str((end-9):(end-5)));
OUT.3{j, 1} = bin2dec(bin_str((end-4):end));
if strcmp(bin_str(end-10), '1')
OUT.4{j, 1} = 'T';
else
OUT.5{j, 1} = 'R';
end
end
I have a cell array (HEX_DATA) containing hex strings. I want to use cellfun to convert all from hex to binary. I need some help with how to compose the command. This is what I've tried so far. Is this possible?
BIN_DATA = cellfun(@x dec2bin(hex2dec(x),8), HEX_DATA);
Error: Unexpected MATLAB expression.
Is there a way for me to use cellfun to pull specifing parts of the binary string, perform a bin2dec, and output them into separate cell arrays? Would it be something like:
OUT.1 = cellfun(@bin2dec, BIN_DATA{:,1}(1:(end-11)));
Cheers, Mike
回答(2 个)
Azzi Abdelmalek
2012-11-14
编辑:Azzi Abdelmalek
2012-11-14
HEX_DATA={'0ff';'0f0';'00f'}
BIN_DATA = cellfun(@(x) dec2bin(hex2dec(x),8), HEX_DATA,'un',0)
4 个评论
Jan
2012-11-15
编辑:Jan
2012-11-15
The FOR loop is not nasty. dec2bin and bin2dec are very inefficient as well as hex2dec is. For the later sscanf(Str, '%x') is usually much faster.
"OUT.1" is no valid Matlab symbol, because fieldnames cannot start with a number.
Is "Out" pre-allocated? Otherwise it grows in each iteration and this wastes a lot of time.
Instead of converting the decimal value to a bit-string, the function bitget can obtain the different bits much faster directly from the decimal value:
StrPool = 'TR';
OUT = cell{line_num, 1);
for j=1:line_num
value = sscanf(HEX_DATA{j}, '%x');
S.field1 = bitget(value, 31:-1:11); % No idea which bits you want!
...
S.field4 = StrPool(bitget(value, 11) + 1);
OUT{j} = S;
end
This is not working, but only a code example.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!