我試圖使用可變長度編碼解碼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