Output a string to MATLAB using the fprintf function
Hello, please tell me. I created the matrix
b=250:-50:50
a=linspace(-27,53,5)
w=[a;b]
And now I need to output it using fprintf
with a common header MatrixW:
. I try to do it this way
fprintf( 'MatrixW:%d;%d;%d;%d;%d\r\n', w)
But this way the title is displayed in both the first and second lines. How do I make it shared? Thank you in advance.
2 answers
Here there is a problem more important than the header: fprintf collects the elements of the matrix by columns, and not by rows. As a consequence, the matrix
-27 -7 13 33 53
250 200 150 100 50
Output as
MatrixW: -27;250;-7;200;13
MatrixW: 150;33;100;53;50
Which is hardly acceptable. Replace w
with w'
.
By design, the fprintf command generates and outputs a string over and over again, as long as there is data to output. Therefore, if the title should not be repeated, it should be output separately. For example:
disp('MatrixW:'); fprintf( '%d;%d;%d;%d;%d\n', w');
disp('MatrixW:');
fprintf( '%d;%d;%d;%d;%d\n', w');
This is already a crutch. not only are the columns and rows mixed up, but you can also write more. when given:
A=[1 2; 3 4];
B=[5 6; 7 8];
C=A+B;
That's easier:
disp('Сумма А и В:');
disp(B);
There is also an option like disp(sprintf('матрица %g %g\n',A));
but there is also a mess with rows and columns: /