Using multiple functions in cellfun
5 views (last 30 days)
Show older comments
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
1 Comment
Answers (2)
Azzi Abdelmalek
on 14 Nov 2012
Edited: Azzi Abdelmalek
on 14 Nov 2012
HEX_DATA={'0ff';'0f0';'00f'}
BIN_DATA = cellfun(@(x) dec2bin(hex2dec(x),8), HEX_DATA,'un',0)
4 Comments
Jan
on 15 Nov 2012
Edited: Jan
on 15 Nov 2012
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!