Clear Filters
Clear Filters

replace only nonzeroes with per-column text and value

2 views (last 30 days)
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?

Answers (1)

Star Strider
Star Strider on 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 Comments
Moshe Flam
Moshe Flam on 14 Mar 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 on 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'}

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!