In Octave, I want to convert a string into a matrix of strings. Say I have a string:
s = "one two three one one four five two three five four"
I want to split it into a matrix so that it looks like:
one
two
three
four
five
With duplicates removed.
This code:
words = strsplit(s, ",") %Split the string s using the delimiter ',' and return a cell string array of substrings
Just creates a matrix words
into exactly the same as s
.
How to I convert my string into a matrix of unique words?
The following will also accomplish that:
unique(regexp(string, '[A-z]*', 'match'))
or, alternatively,
unique(regexp(s, '\s', 'split'))
Basically the same as Werner's solution, but it saves a temporary and is more flexible when more complicated matches need to be made.
On matlab:
string = 'one two three one one four five two three five four'
% Convert it to a cell string:
cell_string = strread(string,'%s');
% Now get the unique values:
unique_strings=unique(cell_string,'stable')
If you want char array with the unique values separated with spaces, add the following lines:
unique_strings_with_spaces=cellfun(@(input) [input ' '],unique_strings,'UniformOutput',false) % Add a space to each cell
final_unique_string = cell2mat(unique_strings_with_spaces') % Concatenate cells
final_unique_string = final_unique_string(1:end-1) % Remove white space
Output:
'one two three four five'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With