1

I am working with N-dimensional array and have a problem with the array indexing. I have a task to find an (N-1)-dimensional array in the middle N-dimensional array.

Let me explain in detail with 3D array. A is a 3-dimensional array that has split into groups. In each group, there are b - number of 2-dimensional arrays in the group. I have simulated it as:

b=5;
A=rand(2,2,20);
groups = reshape(A, size(A,1), size(A,2),b, []);

groups is 4-dimensional array, the 4-th dimension is a number of groups ( here it 4).

To find a middle in each group I have added the following loop:

for ii=1:size(groups,4)  % Loop over all groups/slices
     middle(:,:,ii) = groups(:,:,(w-1)/2+1,ii);  % 1 2 3 4 5 : the middle is 3
end

middle is 3-dimensional array that collects middle array in each group.

As you see in my example I have used b=5( odd number). My problem is with even number b.

I have tried to implement it as ( rewrite the loop above);

l=rem(w,2);
 for ii=1:size(groups,4)  % Loop over all groups/slices
     if l==1
         middle(:,:,ii) = groups(:,:,(w-1)/2+1,ii);  
     else
         middle(:,:,ii) = groups(:,:,(w-1)/2,ii);  
     end
 end

But it doesn't work. Matlab gives me an error in the line l=rem(w,2); Could you suggest to me how I can fix it? Is there another way to implement it?

3
  • Out of 1 2 3 4, which one is the "middle"? Commented Jan 15, 2020 at 17:47
  • “Matlab gives me an error in the line l=rem(w,2)”. What is the error? The line seems fine to me. Commented Jan 15, 2020 at 18:06
  • @beaker I was thinking about it. I am going to take an average of 2 and 3 Commented Jan 16, 2020 at 9:48

1 Answer 1

1

You should use floor of ceil to round the index to whichever element you want:

middle_index = floor((w-1)/2+1);

Here, the middle of 4 is 2, using ceil you’d pick index 3.

Next, you can extract the arrays in a single indexing operation:

middle = groups(:,:,middle_index,:);

Finally, use squeeze or reshape to get rid of the 3rd index:

middle = squeeze(middle);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.