使用' for循环'迭代单元格数组

时间:2016-08-26 07:55:05

标签: arrays matlab binary hex cell-array

在matlab中,我有一个带十六进制值的单元格数组块。

a = '40 C0 70 EB'; 
b = '40 C0 80 94'; 
c = '40 C0 90 59';
s = {a;b;c};

我希望以这样的方式水平遍历每一行;

  1. 第一个字节' EB'必须转换为二进制(即EB = 1110 1011 = 8位)并保存在某个变量/数组中

  2. 然后,' EB& 70'必须转换为二进制,但它们的二进制值必须一起存储(即EB& 70 = 11101011 01110000 = 16位)。

  3. 同样,' EB& 70& C0'在某些变量/数组中转换为二进制(即EB& 70& C0 = 11101011 01110000 11000000 = 24位)。

  4. 同样,' 40 C0 70 EB' (即40& C0& 70& EB = 11101011 01110000 11000000 01000000 = 32位)

  5. 最后,必须对其余部分进行同样的事情。

  6. 我编写了一个代码,用于将单个十六进制值转换为等效的二进制值,但我不知道如何从这里开始。

    a = '40 C0 70 EB'; 
    b = '40 C0 80 94'; 
    c = '40 C0 90 59'; 
    
    s = {a;b;c};
    
    s = cellfun(@strsplit, s, 'UniformOutput', false);
    
    s = vertcat(s{:}); 
    
    dec = hex2dec(s);
    bin = dec2bin(dec);
    x=cellstr(bin);
    bin = mat2cell(x, repmat(size(s,1),1,size(s,2)));    
    

    有关如何完成这些专长的任何建议?

1 个答案:

答案 0 :(得分:0)

从你问题中包含的代码来看,你似乎是大部分时间。

这一点我认为你缺少的是如何连接二进制单词,这在Matlab中有点尴尬。有关提示,请参阅this post。但是对于您的示例,只需转换为字符串和连接的轻微hack-y选项可能更容易。

使用您的代码,下面的示例输出:

'11101011'    '1110101101110000'    '111010110111000011000000'    '11101011011100001100000001000000'
'10010100'    '1001010010000000'    '100101001000000011000000'    '10010100100000001100000001000000'
'01011001'    '0101100110010000'    '010110011001000011000000'    '01011001100100001100000001000000'

我认为这是你想要的,但是你的文字并不完全确定。我假设您要保留每行的所有4个数字(8位,16位,24位和32位),因此总共有12个二进制字符串。

a = '40 C0 70 EB'; 
b = '40 C0 80 94'; 
c = '40 C0 90 59'; 

s = {a;b;c};
s = cellfun(@strsplit, s, 'UniformOutput', false);
s = vertcat(s{:});

% Empty cell to store output binary strings;
outputBinary = cell(size(s));
outputDec = zeros(size(s));

% Iterate over each row
for rowNum = 1:size(s,1)

    % To build up binary string from left to right
    binaryString = [];

    % Iterate over each column
    for colNum = 1:size(s,2)

        % Convert hex -> dec -> 8-bit binary word
        % and add new word to end of growing string for this row
        thisBinary = dec2bin(hex2dec(s{rowNum,end+1-colNum}), 8);
        binaryString = [binaryString, thisBinary]; %#ok<AGROW>

        % Save solution to output array:
        outputBinary{rowNum, colNum} = binaryString;
        outputDec(rowNum, colNum) = bin2dec(binaryString);
    end
end

% Display result
format long;
disp(outputBinary);