How to get the length (number of rows) of this Matlab matrix?

I am completely new to Matlab and I just need to change a very small thing in the code. I have the following matrix:

ans = 1 1 1 1 2 1 2 1 1 2 2 2 

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

+4
source share
5 answers

You should use the size function:

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

Just use the size function

 size(ans, 1) 

But if you ask about it, I suggest you work with some basic Matlab tutorials before continuing ...

+3
source

I find it more readable to determine first

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

and then use, for example, the following:

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

It may look like a small saving, but size(.., 1) should be one of the most used functions.

(By the way, switching to such a matrix may not be the best choice for critical code. But if this is not a problem, go to the most readable choice.)

+1
source

To count the number of rows in a matrix:

  length(ans) 

gives the maximum dimension of the matrix. For a 2-dimensional matrix, this is more of the number of rows and columns. I read in the tutorial that length gives the first dimension different from one, but this is incorrect according to the official MATLAB MathWorks documentation and seems to be the cause of the error in the program I am using.

0
source

You can also count the number of rows and columns using one call:

 [rows columns] = size(myMatrix); 
0
source

Source: https://habr.com/ru/post/1487433/


All Articles