繁体   English   中英

octave / matlab - 将字符串转换为唯一字的矩阵

[英]octave/matlab - convert string into matrix of unique words

在Octave中,我想将字符串转换为字符串矩阵。 说我有一个字符串:

s = "one two three one one four five two three five four"

我想将其拆分为矩阵,使其看起来像:

one
two
three
four
five

删除重复项。

这段代码:

words = strsplit(s, ",") %Split the string s using the delimiter ',' and return a cell string array of substrings

只需创建一个与s完全相同的矩阵words

如何将我的字符串转换为独特单词矩阵?

以下内容也将实现:

unique(regexp(string, '[A-z]*', 'match'))

或者,或者,

unique(regexp(s, '\s', 'split'))

基本上与Werner的解决方案相同,但它可以节省临时性,并且在需要进行更复杂的匹配时更灵活。

在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')

如果希望char数组具有用空格分隔的唯一值,请添加以下行:

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

输出:

'one two three four five'

words = unique( strsplit ('一二三一一四有五二三五四',''))

words =

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM