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.
28 ビュー (過去 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:
2 件のコメント
参考
カテゴリ
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!