0

How can I access an element of an n-D matrix where index comes from a mathematical operation in Matlab?

For example I have a 4D Matrix called A.
I want to access element 1,1,1,1 which results from (3,4,5,6) - (2,3,4,5)

Is there any way I can do this assuming that the array can be any dimension d and that the array from subtraction will always be d elements long?

anon
  • 188
  • 1
  • 13

2 Answers2

1

One possible way would be to utilise the fact that MATLAB can use linear indexing for any n-dimensional array as well as row-column type indexing. Then you just have to calculate the linear index of your operation result.

There may be a more elegant way to do this but if x is the array holding the result of your operation, then the following works

element = A(sum((x-1).*(size(A).^[0:length(size(A))-1]))+1);

The sub2ind function feels like it should help here, but doesn't seem to.

etmuse
  • 505
  • 2
  • 9
0

Another approach is to converting to a cell array, then to a comma-separated list:

A = rand(3,4,5,6); % example A
t = [2 1 3 4]; % example index
u = num2cell(t);
result = A(u{:});
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147