octave/matlab - convert string into matrix of unique words

坚强是说给别人听的谎言 提交于 2019-12-10 17:12:20

问题


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?


回答1:


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.




回答2:


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'



回答3:


words=unique(strsplit('one two three one one four five two three five four',' '))

words =

'five'    'four'    'one'    'three'    'two'


来源:https://stackoverflow.com/questions/17576191/octave-matlab-convert-string-into-matrix-of-unique-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!