Why does size(X, 100) return 1?
조회 수: 11 (최근 30일)
이전 댓글 표시
Here is a code snippet
X = data(:, 1:2); % X is a 2 x 3 matrix for example
disp(size(X, 1)); % displays 2
disp(size(X, 2)); % displays 3
disp(size(X, 5)); % displays 1
disp(size(X, 100)); % displays 1
Why does anything that exceeds the matrix bounds return a 1? Thanks.
댓글 수: 0
채택된 답변
John D'Errico
2020년 4월 29일
편집: John D'Errico
2020년 4월 29일
Because that is how MATLAB works. Any array of finite size is treated as one with infinitely many trailing dimensions of size 1.
So an array of size 2x2 is the same as an array of size 2x2x1. The 2x2 array is simply the first plane of an equivalent multidimensional array. That makes some sense, since if you asked how many 2x2 arrays you had, there is exactly 1 of them. In turn, that 2x2 array is treated as a 2x2x1x1x1x1x1x... array.
This is consistent with how vectors work, and how they always did work, even before MATLAB had multidimensional arrays (a long time ago, in a galaxy far, far away.) That is, a column vector of length n has always been treated as effectively an nx1 array. Note the trailing unit dimension.
Could they have done it differently? Perhaps make size return a NaN if you look too far? I suppose so, but is it a problem as they did it? Size does what it is designed to do, and that is all that matters. The help docs for size do state this behavior.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!