Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

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 vue (au cours des 30 derniers jours)
Michael Tross
Michael Tross le 14 Nov 2019
Clôturé : MATLAB Answer Bot le 20 Août 2021
"( 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 commentaires
Daniel M
Daniel M le 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');
Michael Tross
Michael Tross le 14 Nov 2019
Modifié(e) : Michael Tross le 14 Nov 2019
Thank you Daniel! That did the trick!

Réponses (1)

Stephen23
Stephen23 le 14 Nov 2019
Modifié(e) : Stephen23 le 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 commentaire
Daniel M
Daniel M le 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.

Cette question est clôturée.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by