使用 'for loop' 遍历元胞数组

Using a 'for loop' to iterate through a 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位)保存在variable/array

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

  3. 类似地,'EB & 70 & C0'在一些variable/array.

    [=中转换为二进制(即EB & 70 & C0 = 11101011 01110000 11000000 = 24位) 37=]
  4. 类似地,'40 C0 70 EB'(即 40 & C0 & 70 & EB = 11101011 01110000 11000000 01000000 = 32 位)

  5. 最后,对其余的行进行同样的操作。

我已经编写了将各个十六进制值转换为等效二进制值的代码,但我不确定如何从这里继续。

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)));    

关于如何完成这些壮举有什么建议吗?

从您问题中包含的代码来看,您似乎已经完成了大部分工作。

我认为您缺少的这一点是如何连接二进制单词,这在 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);