4

In MATLAB, I have a multidimensional array of floats, A, with m dimensions; that is, its entries can be referenced with A(n_1, n_2, ..., n_m).

I don't know if there is a good way to describe this using technical terms, so let me just use an example: if A is a 4-dimensional array, then

A(:,:,1,:) is a 1st cross section of A in the 3rd coordinate. Similarly,

A(:,2,1,:) would be the (2,1)th cross section of A in the 2nd and 3rd coordinates.

So my general question is, given an A whose dimensions are only determined at runtime, how do I reference the (k_1,...,k_j)th cross section of A in the (c_1,...,c_j) coordinates, where the k's and c's are also variables?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • I asked a similar question [here](http://stackoverflow.com/questions/10146082/indexing-of-unknown-dimensional-matrix), but see now that it doesn't immediately solve your question. Ignore my vote to duplicate/close – Gunther Struyf Jun 04 '13 at 07:20

2 Answers2

1

You need to index A using a cell-array:

% Create array
A = rand(4,4,4,4);

% example k & c
k = [3 4 4];
c = [1 3 4];   


% Things that can go wrong
szA = size(A);
if numel(k) ~= numel(c) || any(c > ndims(A)) || any(k > szA(c)) 
    error('Invalid input.'); end


% Create the cell { ':' ':' ':' ... } with 
% the correct amount of repetitions
R = repmat({':'}, 1,ndims(A));

% Change it to { [3] ':' [4] [4] } 
% (depending on k and c of course)
R(c) = num2cell(k);

% use it to reference A
A(R{:})
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
0

I dont have matlab so I cant confirm this but I suspect the answer is:

function [val] = get_cross_value(A, cross_section, coord) {
     cross_A =  squeeze(A(cross_section{:}));
     val = squeeze(cross_A(coord));
} 

My info came from http://www.mathworks.com/matlabcentral/newsreader/view_thread/166539

cacba
  • 413
  • 4
  • 9