Reputation: 14674
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
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
Reputation: 3009
Also you can get both rows and columns count using one call:
[rows columns] = size(myMatrix);
Upvotes: 2
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
Reputation: 53809
You should use the size function:
nRows = size(myMatrix, 1); % 1 stands for the first dimension
Upvotes: 10