# Question on peculiar behaviour of multidimensional array indexing in matlab function gradient()

Discussion in 'MATLAB' started by Kasper Marstal, May 7, 2009.

1. ### Kasper MarstalGuest

Hello,

I'm trying to tweak the gradient()-function for use in a massive parallel computation. I'm feeding workers with subvolumes of MR images and need to compute gradients of pixel intensities at some point. I'm replacing the calculations of differences on left and right edges, treating them as differences on interior points using pixels from neighbor subvolumes. My function is this (not including my treating of inputs):

for k = 1:ndim
siz = size(D)-2*h;
n = siz(1);
p = siz(2);
hArr = loc{k});

% Take centered differences on interior points
hArr = hArr(2*h+1:end) - hArr(1:n);
g = (D(2*h+1:end,h+1:h+p) - D(1:n,h+1:h+p)) ./ hArr,ones(p,1));

varargout{k} = ipermute(g,[k:ndim 1:k-1]);
size(varargout)

% Set up for next pass through the loop
D = permute(D,perm);
end

It is almost the same as the built-in gradient only with slight modifications in indexing and I removed the calculations of differences on edges. When fed with 3-dim arrays it only returns 2-dimensional arrays (which as far as I can see makes perfectly good sense) . I don't understand how matlab's built in gradient

% Take centered differences on interior points
if n > 2
h = h(3:n) - h(1:n-2);
g(2:n-1, = (f(3:n,-f(1:n-2,)./h,ones(p,1));
end

can access the other dimensions in f with only 2-dim subscripts? And seeing that it indeed works, how come my call to g and D not work in the same way?

Thank you for reading my question.

Kasper

Kasper Marstal, May 7, 2009