'Matlab - replace values in a string of numbers
I'm new to Matlab. I have a stream (string) of numbers, like '1123412211'. Then I have the Huffman code for each number:
>> code{:,1}
ans =
'010'
ans =
'011'
ans =
'00'
ans =
'1'
I would like to obtain the bit stream by replacing 1 with 010, 2 with 011 and so on.
for i=1:length(p)
stream = strrep(stream,i,code{i,1});
end
where p is the array containing the probabilities of each values.
This is not working as it gives a warning and does not replace the values:
Warning: Inputs must be character vectors, cell arrays of character vectors, or string arrays.
Do you have any suggestion?
Solution 1:[1]
The reason you're getting an error is that all off the arguments to strrep need to be arrays of characters or strings and I is a number. Try this instead:
stream = strip(stream, num2str(i, '%i'), code{i,1});
num2str will convert the input number to a character array and the optional second argument here is used to specify that it should be treated as a signed integer.
Note: The approach you are using may cause you issues as you have the string 1 in both your input array and substitutions. If you're not careful about the replacement order you won't get what you expect.
Solution 2:[2]
Consider using replace with vector inputs. At each position in the string, replace will try to match an entry in the old value input and will prefer the first match. If there is ever a string element that is a prefix of another string element, make sure the preferred behavior is first in the array.
>> values = string(1:5)
values =
1×5 string array
"1" "2" "3" "4" "5"
>> huff = ["a" "b" "c" "d" "e"]
huff =
1×5 string array
"a" "b" "c" "d" "e"
>> replace("12321", values, huff)
ans =
"abcba"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GrapefruitIsAwesome |
| Solution 2 | matlabbit |
