sprintf/fprintf help

조회 수: 90 (최근 30일)
Kelvin Luo
Kelvin Luo 2017년 5월 30일
답변: Rik 2017년 5월 30일
n=10 if i want the output to say "You have done this activity 10 times" how would i write it? I know for fprintf('You have done this activity \n'), the n would go in there, but is there a write is so that i could include words after \n? And should i use sprintf or fprintf?

채택된 답변

Star Strider
Star Strider 2017년 5월 30일
Try this:
N = 10;
str = sprintf('You have done this activity %d times.\n', N);
or:
fprintf(fido, 'You have done this activity %d times.\n', N)
The fprintf function prints its output to the Command Window or to a file (identified by ‘fido’ here, and created by the fopen function).
The sprintf function outputs to a string (here the ‘str’ variable) that you can use for other purposes, for example a text object, plot title, xlabel, ylabel, zlabel and other situations where you want formatted output.
See the documentation for the various functions for a full description of their capabilities.

추가 답변 (1개)

Rik
Rik 2017년 5월 30일
You should have a look at the documentation. Just type doc sprintf and it will open.
fprintf writes (prints) a formatted string to a file (the command output counts as a file in this case), sprintf writes a formatted string. That means that the second can be used to create a variable. In your case you need to use this:
fprintf('You have done this activity %d times \n',n)
The %d means that the first extra input should be converted to a digit, the \n is simply a new line indicator. For a full list of the possibilities and other special characters, just have a look at the documentation. That solves most of the problems (a second option is to [insert favorite search engine] an example)

카테고리

Help CenterFile Exchange에서 Install Products에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by