[英]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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.