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?
Note that if a matrix has two entries in each row, then the matrix has two columns. Similarly, if a matrix has two entries in each column, then it must have two rows.
If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns.
If you want to access all of the rows or columns, use the colon operator by itself. For example, return the entire third column of A . In general, you can use indexing to access elements of any array in MATLAB regardless of its data type or dimensions.
Use len(arr) to find the number of row from 2d array. To find the number columns use len(arr[0]).
Use the size()
function.
>> size(A,2) Ans = 3
The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.
Official documentation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With