[matlab] How to get the number of columns in a matrix?

Suppose I specify a matrix A like

A = [1 2 3; 4 5 6; 7 8 9]

how can I query A (without using length(A)) to find out it has 3 columns?

This question is related to matlab

The answer is


While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.


When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.