Auto Squeeze Problem in Array Indexing

8 views (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 15 Dec 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.

More Answers (1)

Guillaume
Guillaume on 15 Dec 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 Comments
Walter Roberson
Walter Roberson on 15 Dec 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
Ozgun Savas on 16 Dec 2015
I came to the conclusion that thing that I asked cannot be done in MATLAB and I have to pass that information specifically, as you suggested.
So, I changed my code in that manner.
Thank you.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!