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 1 st cross section of A
in the 3 rd coordinate. Similarly,
A(:,2,1,:)
would be the (2,1) th cross section of A
in the 2 nd and 3 rd 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?
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{:})
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.