フィルターのクリア

replace only nonzeroes with per-column text and value

2 ビュー (過去 30 日間)
Moshe Flam
Moshe Flam 2018 年 3 月 13 日
コメント済み: Star Strider 2018 年 3 月 14 日
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?

回答 (1 件)

Star Strider
Star Strider 2018 年 3 月 13 日
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 件のコメント
Moshe Flam
Moshe Flam 2018 年 3 月 14 日
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 2018 年 3 月 14 日
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'}

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by