gurehbgui
gurehbgui

Reputation: 14674

how to get the length (count of rows) of this matlab matrix?

I'm quite new to matlab and just need to change a very small thing in a code. I have the following matrix:

ans =

     1     1     1
     1     2     1
     2     1     1
     2     2     2

how to get the count of rows of this ans? it should be 4

Upvotes: 8

Views: 33307

Answers (5)

Dan
Dan

Reputation: 45741

Just use the size function

size(ans, 1)

Upvotes: 3

Nilesh Sarkar
Nilesh Sarkar

Reputation: 11

To count number of rows in a matrix:

 length(ans)

gives the maximum dimension of a matrix. For a 2 dimensional matrix, it is the larger of the number of rows and columns. I had read in a tutorial that length gives the first non-singleton dimension, but this is incorrect according to the official MathWorks MATLAB documentation and appears to be the cause of a bug in a program that I am using.

Upvotes: 1

Temak
Temak

Reputation: 3009

Also you can get both rows and columns count using one call:

[rows columns] = size(myMatrix);

Upvotes: 2

Evgeni Sergeev
Evgeni Sergeev

Reputation: 23583

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:

for y = 1:rows(myMatrix)
    for x = 1:cols(myMatrix)
        do_whatever(myMatrix(y,x))
    end
end

It might appear as a small saving, but size(.., 1) must be one of the most commonly used functions.

(By the way, looping over a matrix like this might not be the best choice for performance-critical code. But if that's not an issue, then go for the most readable choice.)

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53809

You should use the size function:

nRows = size(myMatrix, 1);  % 1 stands for the first dimension

Upvotes: 10

Related Questions