Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of columns in a matrix?

Tags:

matlab

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?

like image 493
andandandand Avatar asked Oct 21 '11 02:10

andandandand


People also ask

How many columns does a matrix have?

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.

How do you count rows and columns in a matrix?

If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns.

How do you find the rows and columns of a matrix in Matlab?

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.

How do you find the number of columns in a matrix in python?

Use len(arr) to find the number of row from 2d array. To find the number columns use len(arr[0]).


2 Answers

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.

like image 84
Scottie T Avatar answered Sep 23 '22 23:09

Scottie T


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.

like image 29
Evgeni Sergeev Avatar answered Sep 22 '22 23:09

Evgeni Sergeev