查找并替换单元格数组中的单词

时间:2012-11-19 18:33:54

标签: matlab

我有一个4902x1单元格数组,其中包含像Blue这样的字符串。或者绿色。我想用另一个单词替换这些字符串。如何在MATLAB中完成?

例如找

Blue.
Red. 
Green.

替换为:

Colour.

编辑:

strArray = {'green.','black.'};
strMatch = strmatch(strArray, Book2);
strArray( strMatch(str,strArray)) = {'colour'};

2 个答案:

答案 0 :(得分:2)

为什么不使用

strArray( strmatch(str,strArray) ) = {'newString'};

在此示例中,您需要将变量str设置为您要搜索的字符串, 例如str ='绿色。'

编辑:已更新,以反映您对原始帖子的修改。

strArray = {'green.','black.'};
strMatch = strmatch(strArray, Book2); % This line is unnecessary and if Book2 is not a string variable it will not work

strArray( strMatch(str,strArray)) = {'colour'}; % For this line to work you need declare a string value for the variable str, e.g. str='green.'

答案 1 :(得分:2)

如果你有一个字符串的单元格数组(在你的例子中,strArray不是一个单元格数组),我会定义一个小函数来执行逻辑,然后使用cellfun

function y = changecolor(str)
if( strcmpi('green',str) || strcmpi('blue',str) )
    y = 'color';
else
    y = str;
end

然后您可以使用以下命令获取新数组:

changed_array = cellfun(@changecolor, strCellArray,'Uniform',false)
相关问题