필터 지우기
필터 지우기

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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by