Why does size(X, 100) return 1?
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Justin Montanaro
il 29 Apr 2020
Commentato: Stephen23
il 29 Apr 2020
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 Commenti
Risposta accettata
John D'Errico
il 29 Apr 2020
Modificato: John D'Errico
il 29 Apr 2020
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.
1 Commento
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!