Borrar filtros
Borrar filtros

replace only nonzeroes with per-column text and value

2 visualizaciones (últimos 30 días)
Moshe Flam
Moshe Flam el 13 de Mzo. de 2018
Comentada: Star Strider el 14 de Mzo. de 2018
I have a vector:
data = [11,111; 0,222; 33,0; 0,0; 55,555];
I want a string (or char) array like this:
result:
['foo:11,bar:111'; ...
'bar:222'; ...
''; ...
'foo:44'; ...
'foo:55,bar:555']
I want to conditionally replace the numbers with strings. If the value is zero I want an empty string. If the value is non-zero I want a prefix for each column and the value.
How do I do this?
strcat cannot do something conditionally. sprintf creates a single horizontal string. string() cannot concatenate.
I'll need `data>0` but then what?

Respuestas (1)

Star Strider
Star Strider el 13 de Mzo. de 2018
Try this:
data = [11,111; 0,222; 33,0; 0,0; 55,555];
strvct = sprintf('foo:%d\tbar:%d\n', data');
result = regexprep(strvct, '(foo:0|bar:0)', ' ')
result =
'foo:11 bar:111
bar:222
foo:33
foo:55 bar:555
  2 comentarios
Moshe Flam
Moshe Flam el 14 de Mzo. de 2018
Basically your answer is `sprintf` with `\n` I like that.
But I'm waiting to see if someone can come up without the regexp.
I would rather do two replacements, once of the zeroes and once of the nonzeroes and then concat the replacements.
Is there a way to map an action or a conditional action to each cell? If so I can convert to a cell array or string array with the text (of the numbers) and then do the two conditional `replace` and `strcat`.
Star Strider
Star Strider el 14 de Mzo. de 2018
I’m not certain what you want in terms of code.
This seems to be reasonably efficient:
data = [11,111; 0,222; 33,0; 0,0; 55,555];
strvct = sprintf('foo:%d\nbar:%d\n', data');
celvct = regexp(strvct, '\n', 'split');
idx = cellfun(@isempty, regexp(celvct(1:end-1), '(:0)$'));
result = celvct(idx)
result =
1×6 cell array
{'foo:11'} {'bar:111'} {'bar:222'} {'foo:33'} {'foo:55'} {'bar:555'}

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by