How to display two or more values in one fprintf line?

263 vues (au cours des 30 derniers jours)
goodwin membreve
goodwin membreve le 28 Oct 2020
r=[1 3];
fprintf('The roots of the equation are %d and %d',r)
How to make the display as "The roots of the equation are 1 and 3."
  2 commentaires
Walter Roberson
Walter Roberson le 28 Oct 2020
That code already does -- but you probably want to add a \n
fprintf('The roots of the equation are %d and %d\n',r)
goodwin membreve
goodwin membreve le 28 Oct 2020
yay thanks!!!! :-)

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 28 Oct 2020
The trick to sprintf() and fprintf() is that each value in memory advances to the next format element. So if you have
r = 1:2; a = [7 13];
fprintf('row %d, a = %d\n', r, a);
It would be natural to expect that the first element of r would be paired with the first element of a giving "row 1, a = 7" as the first output line -- matching format elements to parameters. But that does not happen. Instead, the row %d consumes the first entry in r, the a = %d format entry consumes the second element in r, so "row 1, a = 2" gets printed out. Then next cycle, the row %d moves on to the next available item from memory, and having finished r, moves on to a, so you end up with "row 7, a = 13" as the second output line.
The result is much as-if you had coded
fprintf('row %d, a = %d\n', [r(:); a(:)])
putting all of the variables into one big stream of data, next available location goes to the next available format item.
Because of this, you will tend to see people write code such as
fprintf('row %d, a = %d\n', [r(:), a(:)].')
which builds multiple columns and then transposes into multiple rows, [r(1) a(1); r(2) a(2)] transposed to [r(1) r(2); a(1) a(2)] the in-memory order of which would be [r(1) a(1) r(2) a(2)] so everything gets parcelled out to the correct format descriptor.
It is an oddity of MATLAB that you kind of get used to, but it can get a bit clunky.
Fortunately, as of R2016b, there is a new compose() operation, which does go variable by variable, so that first element of the first variable would go with the row =, and the first element of the second variable would go with the second . But you need to pass in as columns for that to work:
result = compose('row %d, a = %d\n', r(:), a(:));
This will not display to screen or send to file: it is strictly for formatting. You would tend to then do something like
fprintf('%s', strjoin(result))

Plus de réponses (0)

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by