我试图使用可变长度编码解码1和0的数组。例如,如果字符串是[1 0 1 1]
,A = [1 0]
和B = [1 1]
,我的程序应该给我一个字符串,如:['A', 'B']
。如何填充空字符数组?
我首先创建一个空的字符数组x = repmat(char(0),1,10)
但现在当我发现使用for循环和if语句的码字,我怎么字符添加到这个阵列x
?它会显示解码字符串中的字符吗?
我试图使用可变长度编码解码1和0的数组。例如,如果字符串是[1 0 1 1]
,A = [1 0]
和B = [1 1]
,我的程序应该给我一个字符串,如:['A', 'B']
。如何填充空字符数组?
我首先创建一个空的字符数组x = repmat(char(0),1,10)
但现在当我发现使用for循环和if语句的码字,我怎么字符添加到这个阵列x
?它会显示解码字符串中的字符吗?
首先,预先定义的x
长度在MATLAB不必要的,因为语言允许您调整在即时阵列。这就是说,预分配有时是一个好主意,因为它运行得更快。
假设要预先分配的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
的长度。
您可以将字符数组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
如果x的长度为零,则第二个代码段将返回错误。 >> x(end)= 2 试图访问x(0);索引必须是正整数或逻辑。 即使它是预先分配的并且长度不是零,x的最后一个元素会不断被覆盖,是否正确?根据解码的执行情况,有必要更新计数器变量或在for循环中使用迭代变量。 – Falimond
我收到一个错误。我的程序逐个检查代码中的每一位。假设A = [1 1],B = [1 0 1]和C = [1 0 0]。例如,如果我的代码字是代码= [1 0 1 1 1],它将首先检查代码),其中n = 1。如果代码(n)== 1,它将检查代码(n + 1)是否为0。然后如果它是真的,它检查代码(n + 3)。如果代码(n + 3)== 1,那么它知道它将字母存储为'B',否则将存储为C.当代码字很短时出现问题。就好像它是[1 0 1]。当它检查代码(n + 3)时,它什么都没发现,因为代码字已经结束,所以它返回一个错误。我该如何解决? – Kaya311
@ Kaya311看看我添加的代码是否有帮助。您应该能够轻松扩展字典或在必要时进行小的更改。当然,这并不包含检查损坏的消息 - 假定一个完美有效的消息,没有未知的代码序列。 – Falimond