Avoid +0 when using fprintf %+d

조회 수: 14 (최근 30일)
giannit
giannit 2020년 6월 1일
댓글: giannit 2020년 6월 1일
Consider the code
names={'aba','cda','efa','fea','pod'};
numbers=randi([-1 1],5,4);
for i=1:5
fprintf('|%s|%+d|%+d|%+d|%+d|\n',names{i},numbers(i,:))
end
whose output is similar to
|aba|+0|+1|+1|+1|
|cda|-1|+1|-1|+1|
|efa|+1|+0|-1|-1|
|fea|+1|+0|-1|+1|
|pod|+1|-1|-1|-1|
Is there a way to remove the plus in front of the 0s, or to not print + when the number is 0?

채택된 답변

dpb
dpb 2020년 6월 1일
편집: dpb 2020년 6월 1일
Not w/o some code logic of one form or the other, no. There is no "magic bullet" format descriptor that behaves as desired; as you notice, the '+' adds the sign to any numeric field. There also is no conditional formatting expression built in like an Excel format expression.
You could, however, build the format string dynamically and insert the plus only where the values aren't zero. Or, (in a somewhat less elegant solution imo) you could write the output string to a variable first and then do character substitution on it before displaying or writing to file or whatever it is that is the end objective.
The latter is, of course, a trivial change to implement even if somewhat klunky--
for i=1:5
str=sprintf('|%s|%+d|%+d|%+d|%+d|\n',names{i},numbers(i,:));
fprintf('%s\n',strrep(str,'+0',' 0'))
end
Let's see on the former...scratch, stratch...emmm....ah! OK, here, try this:
>> fmts={'% d|','%+d|'};
>> disp(cell2mat([compose('|%s|',string(names.')) compose(fmts((numbers~=0)+1),numbers)]))
|aba|+1|+1|-1|+1|
|cda|-1|+1| 0| 0|
|efa|+1|-1| 0|+1|
|fea|-1| 0|-1| 0|
|pod|+1| 0| 0|-1|
>>
  댓글 수: 1
giannit
giannit 2020년 6월 1일
Thank you for both solutions!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Author Block Masks에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by