Info
此问题已关闭。 请重新打开它进行编辑或回答。
How do I locate all integer values within a matrix (of string and integer values in the same cell), then replace all those integer values with a 1 or 0 thus forming a new matrix with the replaced integers?
1 次查看(过去 30 天)
显示 更早的评论
"( x(2) | x(1) )"
"x(3)"
"( x(4) | x(6) | x(5) )"
"( x(7) | x(8) )"
"( x(7) | x(8) )"
""
"x(9)"
"( x(10) & x(11) & x(12) )"
"x(13)"
"( x(15) | x(14) | x(1) )"
The text above are in a column vector, but I need to replace the integers with a zero or one. Eg. All integer values not equal to two should be zeros (x(0)), whereas those equal to two should be '1' (x(1)
4 个评论
Daniel M
2019-11-14
I know there's a way to do this in one line, but I'm not great with regular expressions. Here's what I came up with, perhaps you can make it more elegant.
s = ["( x(2) | x(1) )", "x(3)", "( x(4) | x(6) | x(5) )", "( x(7) | x(8) )", "( x(7) | x(8) )", "", "x(9)", "( x(10) & x(11) & x(12) )", "x(13)", "( x(15) | x(14) | x(1) )"];
r = regexprep(s,'\(2\)','(NaN)');
r = regexprep(r,'\(\d*\)','(0)');
r = regexprep(r,'NaN','1');
回答(1 个)
Stephen23
2019-11-14
编辑:Stephen23
2019-11-14
Method one: multiple regular expressions in one regexprep call:
>> c = {'( x(2) | x(1) )', 'x(3)', '( x(4) | x(6) | x(5) )', '( x(7) | x(8) )', '( x(7) | x(8) )', '', 'x(9)', '( x(10) & x(11) & x(12) )', 'x(13)', '( x(15) | x(14) | x(1) )'};
>> d = regexprep(c,{'\(2\)','\d+','%%%'},{'(%%%)','0','1'});
>> d{:}
ans =
( x(1) | x(0) )
ans =
x(0)
ans =
( x(0) | x(0) | x(0) )
ans =
( x(0) | x(0) )
ans =
( x(0) | x(0) )
ans =
''
ans =
x(0)
ans =
( x(0) & x(0) & x(0) )
ans =
x(0)
ans =
( x(0) | x(0) | x(0) )
Method two: dynamic replacement expression:
>> fun = @(x)num2str(isequal(str2double(x),2));
>> d = regexprep(c,'\d+','${fun($&)}');
>> d{:}
ans =
( x(1) | x(0) )
ans =
x(0)
ans =
( x(0) | x(0) | x(0) )
ans =
( x(0) | x(0) )
ans =
( x(0) | x(0) )
ans =
''
ans =
x(0)
ans =
( x(0) & x(0) & x(0) )
ans =
x(0)
ans =
( x(0) | x(0) | x(0) )
See also:
1 个评论
Daniel M
2019-11-14
Ok that is cool. I haven't seen an anonymous function used with regular expressions before. I will definitely be able to make use of this concept.
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!