Jack Twain
Jack Twain

Reputation: 6372

how to print the size of a matrix in a print statement?

I want to print the size of a matrix/vector in a text print statement. Something like this:

fprintf("The size of the matrix is: %s", size(m))

of course it didn't work and I'm unable to find out how.

Edit:
I tried this and it worked, but is there a better way to do it?

fprintf('The size of the matrix is: %s\n', num2str(size(p)))

Upvotes: 1

Views: 832

Answers (4)

Daniel Pereira
Daniel Pereira

Reputation: 421

In fprintf, %s is used for strings. You can use num2str or any of the solutions provided.

fprintf('The size of the matrix is: %s', num2str(size(zeros(10,10))))

Edit 10 years later: A much nicer way:

fprintf('The size of the matrix is: %s', regexprep(num2str(size(zeros(10,11,12))),'\s{1,}','×'))

Returns:

The size of the matrix is: 10×11×12

Upvotes: 5

carandraug
carandraug

Reputation: 13091

First you need to generate the exact template. In order to account for an arbitrary number of dimensions, you can use the following:

octave-cli-3.8.1> a = ones (7, 3, 4, 8);
octave-cli-3.8.1> template = strjoin (repmat ({"%i"}, [1 ndims(a)]), " x ")
template = %i x %i x %i x %i

Then it is just a matter of using it fprintf:

octave-cli-3.8.1> sprintf (["The size is: " template "\n"], size (a))
ans = The size is: 7 x 3 x 4 x 8

Upvotes: 2

sco1
sco1

Reputation: 12214

sprintf('The size of the matrix is: %d x %d', size(m))

Upvotes: 4

YisasL
YisasL

Reputation: 335

sprintf('The size of the matrix is: %s', num2str(size(m)))

You can also do it with:

display(['The size of the matrix is: ' size(m)])

But the result is quite different, so it's up to you.

Upvotes: 1

Related Questions