Auto Squeeze Problem in Array Indexing
Ältere Kommentare anzeigen
Hello everyone,
I have a question regarding array indexing.
I want to have a 3 dimensional array even though the last index of my array is maximum 1.
To be clear, let me give an example. Suppose I want to declare an array;
myArray(1,1,1) = 5;
myArray(1,1,2) = 6;
myArray(1,1,3) = 7;
myArray(1,2,2) = 8;
This gives me perfectly fine 1x2x3 double.
However, if I don't define the second entry in the last index, it squeezes automatically. For instance;
myNewArray(1,1,1) = 5;
myNewArray(1,2,1) = 6;
myNewArray(1,3,1) = 7;
myNewArray(2,2,1) = 8;
Above example gives 2x3 array. (2 dimensional)
But, I want it to be 2x3x1 array. (3 dimensional)
How will I achieve that?
Thanks in advance.
Akzeptierte Antwort
Weitere Antworten (1)
Guillaume
am 15 Dez. 2015
What is the reason behind your request? It's something odd to want.
I don't think it's possible. Matlab automatically removes trailing singleton dimensions. You can still access the elements of a 2d array as if it were 3d and query the size as if it were 3d:
a = ones(5); %2d array
a(3,4,1) %still valid to query using 3d
[rows, cols, pages] = size(a) %pages is 1
5 Kommentare
Ozgun Savas
am 15 Dez. 2015
Guillaume
am 15 Dez. 2015
" I perform a check which requires my array to be 3D" How?
The thing is for matlab, a 2d array is also a 3d array (it's also a 4d, 5d, etc. array).
There is no reason for a function to fail if it expects a 3d array of arbitrary size. As I shown in my example, you can still get the elements of a 2D array using 3d coordinates, and you can still query its size as a 3D array.
Ozgun Savas
am 15 Dez. 2015
Walter Roberson
am 15 Dez. 2015
If you need to know whether the array was "originally" 4D then you need to pass that information on specifically. If you took a subarray of an array and ended up with a trailing singular dimension then the subarray will have a lower ndims and there is no way of avoiding that. The kind of array it was before it was processed is a piece of state information that cannot in all circumstances be deduced by looking at the array size afterwards.
Exception: possibly if you were to use a mex routine to build the array you could enter a specific trailing 1 in the dimensions and have it reflected when you ask for the size(), but not necessarily if you ask for ndims(). However, as soon as the array was copied or worked with in arithmetic then it would definitely "collapse" into the lower number of dimensions.
Ozgun Savas
am 16 Dez. 2015
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!