Using multiple functions in cellfun

5 Ansichten (letzte 30 Tage)
Mike K
Mike K am 14 Nov. 2012
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

Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 14 Nov. 2012
Bearbeitet: Azzi Abdelmalek am 14 Nov. 2012
HEX_DATA={'0ff';'0f0';'00f'}
BIN_DATA = cellfun(@(x) dec2bin(hex2dec(x),8), HEX_DATA,'un',0)
  4 Kommentare
Mike K
Mike K am 14 Nov. 2012
Looks like reading isn't my strong suit...I copy pasted and it worked like a champ! Thanks Azzi! Do you have any input on how to do the second part of my question?
Azzi Abdelmalek
Azzi Abdelmalek am 14 Nov. 2012
do you mean
OUT= cellfun(@bin2dec, BIN_DATA);

Melden Sie sich an, um zu kommentieren.


Jan
Jan am 15 Nov. 2012
Bearbeitet: Jan am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by