Auto Squeeze Problem in Array Indexing

조회 수: 7 (최근 30일)
Ozgun Savas
Ozgun Savas 2015년 12월 15일
댓글: Ozgun Savas 2015년 12월 16일
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.

채택된 답변

Walter Roberson
Walter Roberson 2015년 12월 15일
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.

추가 답변 (1개)

Guillaume
Guillaume 2015년 12월 15일
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
Walter Roberson
Walter Roberson 2015년 12월 15일
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 2015년 12월 16일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by