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!