user5512412
user5512412

Reputation: 25

MATLAB:how can I use fprintf or sprintf to print matrix and vectors with strings togheter?

I'm at the beginning with the MATLAB software ,and I have two questions:

1) If I want to print a matrix, preceeded by a string, using the fprintf command, how can I do? For example, to print a matrix alone, I use

fprintf([repmat('%d\t', 1, size(r, 2)) '\n'], r');   

But how can I print a string followed by the matrix, all togheter in fprintf, without usind the disp function ? For example, if I want to print:

>>The matrix you inserted is [1 3; 4 6]

2) How can I do the same thing with vectors (I know it's only a particular case of matrix) ? I actually use, for example:

>>vectorname=[1 5 2];
>>strtrim(sprintf('%d  ', vectorname));

And it's ok for the only numbers of the vector, but If I insert a string in spintf the result is:

 >>vectorname=[1 5 2];
 >>strtrim(sprintf('Your vector is:  %d  ', vectorname))

 >>Your vector is 1 Your vector is 5 Your vector is 2

How can I inglobe the numbers, one ofter the other, with only one command (sprintf, fprintf, ecc.)??

Thank you very much for the help!

Upvotes: 1

Views: 4663

Answers (1)

Dev-iL
Dev-iL

Reputation: 24159

In both cases you can use mat2str.

First case:

input_mat = [1 3; 4 6];
sprintf(['The matrix you inserted is ' mat2str(input_mat)])

ans =

The matrix you inserted is [1 3;4 6]

Second case:

vectorname=[1 5 2];
sprintf(['Your vector is: ', mat2str(vectorname)])

ans =

Your vector is: [1 5 2]

Upvotes: 4

Related Questions