Auto Squeeze Problem in Array Indexing
11 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Ozgun Savas
il 15 Dic 2015
Commentato: Ozgun Savas
il 16 Dic 2015
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.
0 Commenti
Risposta accettata
Walter Roberson
il 15 Dic 2015
You cannot do that that in matlab. Matlab always removes trailing singular dimensions. You should be writing your size() with three outputs to capture the trailing dimension as 1, or if you use size with a single output then extend the vector of results with as many trailing 1 as is needed.
0 Commenti
Più risposte (1)
Guillaume
il 15 Dic 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 Commenti
Walter Roberson
il 15 Dic 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.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!