How to display two or more values in one fprintf line?
134 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
goodwin membreve
el 28 de Oct. de 2020
Respondida: Walter Roberson
el 28 de Oct. de 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 comentarios
Walter Roberson
el 28 de Oct. de 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)
Respuesta aceptada
Walter Roberson
el 28 de Oct. de 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))
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Numeric Types en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!