Info
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
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 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
"( 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 Commenti
Daniel M
il 14 Nov 2019
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');
Risposte (1)
Stephen23
il 14 Nov 2019
Modificato: Stephen23
il 14 Nov 2019
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 Commento
Daniel M
il 14 Nov 2019
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.
Questa domanda è chiusa.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!