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 日間)
Michael Tross
Michael Tross 2019 年 11 月 14 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
"( 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
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');
Michael Tross
Michael Tross 2019 年 11 月 14 日
編集済み: Michael Tross 2019 年 11 月 14 日
Thank you Daniel! That did the trick!

回答 (1 件)

Stephen23
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
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!

Translated by