【问题标题】:octave/matlab - convert string into matrix of unique wordsoctave/matlab - 将字符串转换为唯一单词的矩阵
【发布时间】:2013-07-10 16:37:30
【问题描述】:

在 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

只需将矩阵words 创建成与s 完全相同的矩阵。

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

【问题讨论】:

  • 你的分隔符应该是空格,而不是逗号。

标签: matlab vector matrix octave


【解决方案1】:

以下内容也将实现:

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

或者,或者,

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

与Werner的方案基本相同,但它节省了一个临时的,并且在需要进行更复杂的匹配时更加灵活。

【讨论】:

  • 谢谢,但我的脚本/控制台冻结在这一行。我正在使用 Xoctave
  • @Obay:嗯,它在 MATLAB 上运行良好...也许向 Octave 开发人员提交错误报告?
  • 在 octave 3.6.4 中对我来说很好,至少对于像 OP 示例中的短字符串。
【解决方案2】:

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

【讨论】:

  • 谢谢,但第一个代码 sn-p 产生错误:error: textread: couldn't open data file one two three one one four five two three five four
  • @Obay 抱歉回答迟了,请尝试改用textscan。似乎 octave textread 不像 matlab 那样工作。
  • @Obay 第一部分似乎有一个小错误(textread 而不是strread)。现在已修复此问题并确认第一个解决方案适用于 matlab。
【解决方案3】:

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

单词 =

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多