如何填充空字符数组?

时间:2013-11-25 03:07:24

标签: arrays matlab

我正在尝试使用可变长度编码解码1和0的数组。例如,如果字符串是[1 0 1 1]A = [1 0]B = [1 1],我的程序应该给我一个字符串:['A', 'B']

我首先创建了一个空字符数组x = repmat(char(0),1,10)

但是现在当我使用for循环和if语句检测到代码字时,如何将字符添加到此数组x?它会在解码后的字符串中显示字符吗?

2 个答案:

答案 0 :(得分:0)

您可以像对齐数组一样索引字符数组x

x(1) = 'A'; %Assign the char 'A' to the first element of x
.
.
.
x(10) = 'B'; %Assign the char 'B' to the tenth element of x

以下是您想要做的简短示例。

clear decodedMsg
% define a dictionary between codes and corresponding characters
code{1,1} = 'A'; code{1,2} = '11';
code{2,1} = 'B'; code{2,2} = '101';
code{3,1} = 'C'; code{3,2} = '100';

% declare a sample message, corresponds to ABCBA
msg = [1 1 1 0 1 1 0 0 1 0 1 1 1];

%keeps track of the number of matches found, used to add to decodedMsg
counter = 1;
% get length of message and use to iterate through the msg
N = length(msg);
buffer = []; %must declare buffer if you are to use (end + 1) indexing later on
for i = 1:N
    buffer(end + 1) = msg(i);                   %add the next msg value to the buffer
    strBuf = strrep(num2str(buffer),' ','');    %convert buffer into string, e.x. [1 0 1] => '101'
    findMatch = ismember(code(:,2),strBuf);     %findMatch contains a 1 if a match is found
    if any(findMatch)                           %if any element in findMatch is 1
        decodedMsg(counter) = code{findMatch,1};%use that element to index a char in code cell array
        counter = counter + 1;                  %increment counter since another code was found
        buffer = [];                            %reset buffer for next string of 1s and 0s
    end
end

答案 1 :(得分:0)

首先,在MATLAB中预先定义x的长度是不必要的,因为该语言允许您即时调整数组大小。话虽这么说,预分配有时候是一个好主意,因为它运行得更快。

假设您要预先分配x的长度,您可以直接为x中的元素指定一个字符:

% Preallocate x
x = repmat(char(0),1,10);

% Assign a character to x
x(1) = 'A';

您可以将1替换为数组中的任何元素。

这方面的挑战是您需要在此预分配阵列中跟踪您所处的位置。如果您已经将字符写入位置1,2和3,则需要知道下一个赋值将写入x的第4个元素:x(4) = ...

更优雅的解决方案可能如下:

x = [];
if foundLetter
    x(end) = 'A';
end

这会将字母A添加到预定义字符数组x的末尾。它不需要您预先分配x的长度。