I have a variable dimension matrix, X. I want a function that will get the first half of X in one dimension. I.E., I want something like this:
function x = variableSubmatrix(x, d)
if d == 1
switch ndims(x)
case 1
x = x(1:end/2);
case 2
x = x(1:end/2, :);
case 3
x = x(1:end/2, :, :);
(...)
end
elseif d == 2
switch ndims(x)
case 2
x = x(:, 1:end/2);
case 3
x = x(:, 1:end/2, :);
(...)
end
elseif (...)
end
end
I’m not quite sure how to do this. I need it to be fast, as this will be used many times in computation.
This should do the trick:
The above first creates a 1-by-
ndims(x)cell array with':'in each cell. The cell corresponding to dimensiondis then replaced with a vector containing the numbers 1 through half the size of dimensiond. Then, the contents of the cell array are output as a comma-separated list (using the{:}syntax) and used as the indices intox. This works because':'and:are treated the same way (i.e. “all elements of this dimension”) when used in an indexing statement.