4

Matlab defines the matrix function length to return

Length of largest array dimension

What is an example of a use of knowing the largest dimension? Knowing number of rows or columns has obvious uses... but I don't know why someone would want the largest dimension regardless of whether it is rows or cols.

Thank You

Shai
  • 111,146
  • 38
  • 238
  • 371
Max Wen
  • 737
  • 2
  • 10
  • 21
  • 3
    This is a good point and I have seen programs fail because of applying the ``length`` command on matrices. Especially when one expects to get ``size(x, 2)`` because the second dimension should be the largest. I can not see an advantage of allowing ``length`` to be applied on matrices. If I want to know the largest dimension, I would prefer to be more explicit and use ``max(size(x))`` – Nras Dec 30 '14 at 07:53
  • Good point. I think @chappjc will agree with you that it's pretty useless (read [his profile](http://stackoverflow.com/users/2778484/chappjc)) – Luis Mendo Dec 30 '14 at 11:46
  • @Nras I agree with you. Make that an answer! – Luis Mendo Dec 30 '14 at 11:47
  • logically `length()` should return the total number of elements in a matrix regardless of shape. It make no sense to me to return `max(size())` instead. – John Alexiou Dec 30 '14 at 13:13
  • @ja72 That's `numel` – Luis Mendo Dec 31 '14 at 02:27
  • Makes sense. `numel` : number of elements – John Alexiou Dec 31 '14 at 03:58

4 Answers4

3

In fact, most of my code wants to do things exactly once for each row, for each column or for each element.

Therefore, I typically use one of these

size(M,1)
size(M,2)
numel(V)

In particular do not depend on length to match the number of elements in a vector!

The only real convenience that I found {in older versions of matlab} for length is if I need a repeat statement rather than a while. Then it is convenient that length of vectors usually returns at least one.

Some other uses that I had for length:

  • A quick rough check whether something is big.
  • Making something square as mentioned by @Mike
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
  • "In particular do not depend on length to match the number of elements in a vector!" Can you give a reference or an example for this? I.e. when does ``length(x)`` not equal ``numel(x)`` if x is of size ``1 x N`` or ``N x 1``, i.e. a vector. – Nras Dec 30 '14 at 11:03
  • @Nras I see that the problem no longer occurs in newer versions of matlab, but in older ones a statement like `v=ones(0,1) for t=1:length(v), v(t), end` would error out because `length(v)` used to return 1 rather than 0. – Dennis Jaheruddin Dec 30 '14 at 12:23
2

This question addresses a good point and I have seen programs fail because of applying the length command on matrices (for looping). Especially when one expects to get size(M, n) because the n-th dimension should be the largest. In total, I can not see an advantage of allowing length to be applied on matrices, in fact I only see risks from probably unexpected behavior.

If I want to know the largest dimension of any matrix, I would prefer to be more explicit and use max(size(M)), which also should be much clearer for anyone reading this code.

I am not sure, whether the following example should be in this answer, but It somehow addresses the same point. It is also useful to be explicit with dimension, when averaging over matrices. Consider the case, where you always want to average over the first dimension, i.e. over the columns of a matrix. As long as your matrix is of size n x m, where n is greater than 1, you do not have to care about specifying a dimension. But for unforseen cases, where your matrix happens to be a row-vector, things get messy:

%// good case, where num of rows is 2 or greater
size(mean(rand(2, 4), 1)) %// [1, 4]
size(mean(rand(2, 4)))    %// [1, 4]

%// bad case, where num of rows is 1
size(mean(rand(1, 4), 1)) %// [1, 4]
size(mean(rand(1, 4)))    %// [1, 1], returns the average of that row
Nras
  • 4,251
  • 3
  • 25
  • 37
1

If you want to create a square matrix B that can contain the input matrix A which is non-square, you can take the latter's length and use it to initialize the matrix B with zeros where the rows and columns would be of A's length, then copy the input matrix into the new zeroed matrix.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
  • 1
    I decided to modify your answer to make it more verbose. I had a hard time understanding what you wanted to convey. Hope that was ok! – rayryeng Dec 30 '14 at 05:49
  • @rayryeng I was just about posting this comment below, but your answer got deleted meanwhile. Anyhow, here it is: Wow, I thought this was the usual use-case for a down-vote for an answer, which I think is incomplete or wrong. I absolutely did not mean "to be a dick". Once my comment has been adressed and the answer covers my point (which is now done), I for sure remove the down-vote. – Nras Dec 30 '14 at 07:49
  • @Nras - It certainly is a valid use-case for your downvote. I wasn't referencing the downvote in my hostility. I just misinterpreted your phrasing. I thought you were actually being hostile but you were actually being sincere and I apologize. Also, as I was modifying my answer, I figured it was useless to keep it which is why I deleted it. Thank you for pointing out my blunder btw! – rayryeng Dec 30 '14 at 07:50
  • @rayryeng good to hear, you usually provide nice answers, just in this case I did not agree. Good day, Sir! – Nras Dec 30 '14 at 07:52
  • @Nras - In this case, I didn't agree with myself either.... I always use `size` or `numel`. I hate using `length` for that exact reason that you mentioned in your previous comment to me. All the best, and my apologies again! – rayryeng Dec 30 '14 at 07:53
  • @Nras - Also thanks for the answers comment :) I try to make my answers understandable... though sometimes I get carried away. – rayryeng Dec 30 '14 at 08:12
  • 1
    Forgot about this usecase, but length is indeed the quick way to make a large enough square. – Dennis Jaheruddin Dec 30 '14 at 10:48
  • rayryeng, Nras: In the future, could you do this in a discussion instead of on another answer's comments? – Mike DeSimone Dec 30 '14 at 14:05
1

Another example - the one I use most - is when working with vectors. There it is very convenient to work with length instead of size(vec,1) or size(vec,2) as it doesn't matter if it is a row or a column vector.

As @Dennis Jaheruddin pointed out, length gave wrong results for empty vectors in some versions of MATLAB. Using numel instead of length might therefore be convenient for better backward compatibility. The readibility of the code is almost the same IMHO.

This question compares length and numel and their performance, and comes to the result that they perform similarly up to 100k elements in a vector. With more than 100k elements, numel appears to be faster. I tried to verify this (with MATLAB R2014a) and came to the following results:

enter image description here

Here, length is a bit slower, but as it is in the range of micro seconds, I guess it won't be a real difference in speed.

Community
  • 1
  • 1
hbaderts
  • 14,136
  • 4
  • 41
  • 48
  • 1
    In these situations I almost always want to use `numel`. Using length often resulted in 'index exceeds matrix dimensions' when I had empty vectors. – Dennis Jaheruddin Dec 30 '14 at 10:43
  • What is the difference between `length` and `numel` in that use case? `numel([])` and `length([])` both result in `0`. I used `length` and didn't know `numel` so far. – hbaderts Dec 30 '14 at 12:47
  • For new versions this indeed does not appear to be an issue (discovered this after someone commented on my answer). I guess my comment is now mostly relevant if you want improved backwards compatibilty. -- If your goal is convenience, it is worth noting that numel is 1 char shorter, and (in my personal opinion) has a more intuitive definition than length. – Dennis Jaheruddin Dec 30 '14 at 13:02
  • especially since `x(i)` works for both column and row vectors and thus one needs to know the extend of `i` with `length(x)` – John Alexiou Dec 30 '14 at 13:11