필터 지우기
필터 지우기

How can I obtain my expected result?

조회 수: 2 (최근 30일)
Sabid Hossain
Sabid Hossain 2020년 6월 2일
편집: claudio 2020년 6월 2일
I typed this code
function out=picker(c,in1,in2)
if c
out=fprintf('%d\n'in1);
else
out=fprintf('%d\n'in2);
end
my desire was to get this reslut
>>out=picker(true,5,6)
out=5
>>out=picker(false,5,6)
out=6
but matlab found a bug here .What is wrong with my code and how can I obtain my expected result?

채택된 답변

claudio
claudio 2020년 6월 2일
It depends on what type of outcome you need. If you need numeric out
function out = picker(c,in1,in2)
out = in2;
if c, out = in1; end
If you need char outcame
function out = picker(c,in1,in2)
out = sprintf('out = %d',in2)
if c, sprintf('out = %d',in1); end
  댓글 수: 2
Sabid Hossain
Sabid Hossain 2020년 6월 2일
Thank you for you help.I have tried your code by myself and got my desired result.But when I use 'fprintf' instead of 'sprintf' I've got different result.
out = picker(true,4,5)
out = 5
out =
7
out = 4
out =
7
I thought sprintf and fprintf work alike. But when I use fprintf, in result "out = 7" comes out of nowhere. What is the reason behind this?
claudio
claudio 2020년 6월 2일
편집: claudio 2020년 6월 2일
sprintf allows to format data into string. fprintf (with that syntax) returns the number of characters (as Image Analyst said)

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

추가 답변 (2개)

David Hill
David Hill 2020년 6월 2일
function out=picker(c,in1,in2)
if c
out=in1;
else
out=in2;
end
fprintf('out=%d',out);

Image Analyst
Image Analyst 2020년 6월 2일
fprintf() returns the number of characters printed, which is not what you want. What you want is this:
function out = picker(c, in1, in2)
v = [in1, in2];
out = v(c+1);

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by