0

Suppose A is multi-dimensional array (MDA) of size 3,4,5 and B is another MDA of size 3,4,5,6.

I know A(1,:,:) or B(1,:,:,:) can both extract their elements along the first dimension.

I now need to write a general program to extract the k-th dimension from a MDA without knowing its size.

For example, the MDA C has 6 dimension: 4,5,6,7,8,9 and I want an extraction C(:,:,k,:,:,:).

Sometimes, the MDA 'D' has 4 dimension: 3,4,5,6 and I want another extraction D(k,:,:,:).

That is, my problem is the numbers of colon is varying because of the dimension.

Thanks in advance

nam
  • 215
  • 2
  • 11

1 Answers1

1

You can use string arrays to index the array dynamically:

function out = extract(arr,dim,k)  

    subses = repmat({':'}, [1 ndims(arr)]);
    subses(dim) = num2cell(k);
    out = arr(subses{:});

where dim is the dimension in which you want to select and k is an index within that dimension.

I have used a code from this answer: https://stackoverflow.com/a/27975910/3399825

Community
  • 1
  • 1
Addy
  • 1,400
  • 10
  • 20