4

在 MATLAB 中,我有一个多维浮点数组Am也就是说,它的条目可以用A(n_1, n_2, ..., n_m).

不知道有没有什么好的方法可以用技术术语来描述,所以我举个例子:如果A是一个4维数组,那么

A(:,:,1,:)是第3 坐标中的第1横截面。相似地,A

A(:,2,1,:)将是第2和第 3坐标中的第 ( 2,1 )横截面。A

所以我的一般问题是,给定一个A其尺寸仅在运行时确定的,我如何引用坐标中的(k_1,...,k_j)第 th 个横截面,其中's 和's 也是变量?A(c_1,...,c_j)kc

4

2 回答 2

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{:})
于 2013-06-04T05:22:31.313 回答
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

于 2013-06-04T03:02:14.273 回答