Index exceeds matrix dimensions

1 次查看(过去 30 天)
John
John 2016-8-29
A six dimension image/matrix:
for n6 = 1:image_size(6)
img5 = imgin(:,:,:,:,:,n6);
imgout(:,:,:,:,:,n6) = operation5(img5,xout,yout);
end
The img5 is no longer 5 dimension anymore in case one of the first 5 dimensions is "1" and the command in operation5 gives error "Index exceeds matrix dimensions" because it's NOT a 5 dimension any more.
How can keep the dimension even one dimension has size "1"?

回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-8-29
This has nothing to do with the dimension, look at this example
A=[1 1;2 2]
You can write it as you want
A(:,:,1,1,1,1)
Index exceeds matrix dimension, means your are trying to access indices that doesn't exist, like for our example
A(3,1)

Walter Roberson
Walter Roberson 2016-8-29
>> A = ones(1,1,1,1,3)
A(:,:,1,1,1) =
1
A(:,:,1,1,2) =
1
A(:,:,1,1,3) =
1
>> size(A)
ans =
1 1 1 1 3
>> ndims(A)
ans =
5
You can see from this that it is not correct that the array stops being 5 dimensional because one of the first 5 dimensions is 1.
What is correct is that trailing dimensions of size 1 get automatically eliminated.
>> B = ones(1,1,1,3,1)
B(:,:,1,1) =
1
B(:,:,1,2) =
1
B(:,:,1,3) =
1
>> size(B)
ans =
1 1 1 3
>> ndims(B)
ans =
4
This does not, however, mean that you cannot store into there:
>> B(1,1,1,1,3) = 0
B(:,:,1,1,1) =
1
B(:,:,1,2,1) =
1
B(:,:,1,3,1) =
1
B(:,:,1,1,2) =
0
B(:,:,1,2,2) =
0
B(:,:,1,3,2) =
0
B(:,:,1,1,3) =
0
B(:,:,1,2,3) =
0
B(:,:,1,3,3) =
0
>> size(B)
ans =
1 1 1 3 3
it gets automatically extended at need when you store into it. Of course if you try to access a part that is not there then you would have a problem
>> B(1,1,1,1,1,1,2)
Index exceeds matrix dimensions.
the problem is not in specifying 7 input dimensions for a 5 dimensional array: the problem is trying to access memory that is not there. For example, B(1,1,1,1,1,1,1) is fine
My speculation is that your operation5 is not the problem, but that in your
for n6 = 1:image_size(6)
that you defined
image_size = size(imgin)
and when imgin has a trailing dimension of 1, then size() would only automatically return a vector of length 5 instead of a vector of length 6, as size() does not output any trailing 1 beyond the second dimension. There is no way to configure MATLAB to have size() return a vector of a particular length. You could use
[image_size(1), image_size(2), image_size(3), image_size(4), image_size(5), image_size(6)] = size(imgin);
or you could use
image_size = size(imgin);
image_size(end+1:6) = 1; %extend it to length 6 if it is shorter.

类别

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