필터 지우기
필터 지우기

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