You can use linear indexing, if you want to operate on all elements:
X = rand(2,3,4);
Y = zeros(size(X));
for k = 1:numel(X)
Y(k) = X(k) ^ 2;
end
Of course Y = X .^ 2 would be easier without a loop, but this is thought as demonstration only.
If you want to operate on submatrices, you can move them to the first dimensions temporarily:
X = rand(2,3,4,5,6);
operateOn = [3,5];
v = 1:ndims(X);
XX = permute(X, [operateOn, setdiff(v, operateOn)]);
sXX = size(XX);
XX = reshape(XX, [sXX(1:2), prod(sXX(3:end)]);
for k = 1:size(XX, 3)
submatrix = XX(:, :, k);
...
end
Another example is using a cell vector for indexing. If you want a subarray with indexing the the last two dimensions - independent from knowing how many dimensions the input has:
X = rand(2,3,4,5,6);
n = ndims(X);
index = cell(1, n);
index(:) = {':'};
index{end-1} = 3;
index{end} = 4;
Y = X(index{:});
X = rand(2,3,4,5,6);
nv = ndims(X);
v = ones(1, nv);
vLim = size(X);
ready = false;
while ~ready
...
ready = true;
for k = 1:nv
v(k) = v(k) + 1;
if v(k) <= vLim(k)
ready = false;
break;
end
v(k) = 1;
end
end
This is equivalent to the following without the need to know the number of dimensions before:
for i1 = 1:size(X, 1)
for i2 = 1:size(X, 2)
for i3 = 1:size(X, 3)
for i4 = 1:size(X, 4)
for i5 = 1:size(X, 5)
v = [i1, i2, i3, i4, i5];
...
end
end
end
end
end
Best Answer