replace only nonzeroes with per-column text and value
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponses (1)
Star Strider
le 13 Mar 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 commentaires
Star Strider
le 14 Mar 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'}
Voir également
Catégories
En savoir plus sur Cell Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!