Good day. Please can someone explain dimension in simple terms and how it applies to arrays. Also, what do singleton and non-singleton dimension mean and do they affect some builtin functions such as sum.
26 次查看(过去 30 天)
显示 更早的评论
For example sum(M,1) sums over columns and sum(M,2) sums over rows. I am confused because I expect sum(M,1) to be for rows and vice versa because arrays are written in row by column.
1 个评论
Adam
2018-3-15
编辑:Adam
2018-3-15
This is something that is not all that intuitive, or rather, to me the logic is not sufficient that it sticks in my head what ' along dimension dim' means so I always just try it one command line and if I get it the wrong way I do the other one! I could try to just memorise it, but things where there are two options I often have trouble memorising exactly which it is when the logic is not sufficient to me to work it out without having to memorise.
Although the sentence pointed out by Steven Lord, that I hadn't noticed previously, does give a clear logic to remember it by, having said all that!
采纳的回答
Steven Lord
2018-3-15
Two key sentences from the description of the dim input argument in the documentation for the sum function are:
"Dimension dim indicates the dimension whose length reduces to 1. The size(S,dim) is 1, while the sizes of all other dimensions remain the same."
So if you want to squash your matrix down to have 1 row, you sum in dimension 1 which takes the sum of each column of data. If you want to squash your matrix to have 1 column, you sum in dimension 2 which takes the sum of each row.
2 个评论
Steven Lord
2018-3-15
If you call sum with just one input argument, MATLAB reduces the size in the first non-singleton dimension of that input to 1.
For your matrix of size [2 3], the first non-singleton dimension is dimension 1 so the result will be of size [1 3]. That is indeed a row vector.
If you had an array of size [1 2 3], the first non-singleton dimension is the second (the first is a singleton dimension) and the result would be of size [1 1 3]. If you had asked sum to sum that array over dimension 1 instead, the result would have been of size [1 2 3] (in this case there's no reduction to be done.)
更多回答(1 个)
Pawel Jastrzebski
2018-3-15
编辑:Pawel Jastrzebski
2018-3-15
I think you've explained it yourself. It's how Matlab works (opposite to your expectation unfortunately).
- dimension = 1 - carries out the computation along the columns.
- dimension = 2 - carries out the computation along the rows.
- dimension = 3 - carries out the computation along the depth (in 3D matrices).
Also see here:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!