在Matlab中通用化多维数组的索引 [英] Generalise indexing of a multi-dimensional array in Matlab
问题描述
我想归纳为以下任何n
Matlab代码.
I want to generalise to any n
the Matlab code below.
让A
为n
维数组:
clear
rng default
n=4;
A=randn(n,n,n,n);
n=5;
A=randn(n,n,n,n,n);
请注意,A
由n^(n-2)
个二维矩阵组成,每个矩阵的大小为nxn
.
Note that A
is composed of n^(n-2)
2-dimensional matrices, each of size nxn
.
例如,当n=4
时,这些矩阵为A(:,:,1,1),...,A(:,:,4,1),A(:,:,1,2),...,A(:,:,4,4)
.
For example, when n=4
these matrices are A(:,:,1,1),...,A(:,:,4,1),A(:,:,1,2),...,A(:,:,4,4)
.
假设我对以下代码感兴趣:
Suppose I'm interested in a code which:
1)删除每个n^(n-2)
二维矩阵
1) deletes the last column and row in each of the n^(n-2)
2-dimensional matrices
%when n=4
A(n,:,:,:)=[];
A(:,n,:,:)=[];
%when n=5
A(n,:,:,:,:)=[];
A(:,n,:,:,:)=[];
2)删除索引为3th,4th,5th,nth的2维矩阵.
2) deletes the 2-dimensional matrices with the 3-th,4-th,5-th,n-th index equal to n
.
%when n=4
A(:,:,n,:)=[];
A(:,:,:,n)=[];
%when n=5
A(:,:,n,:,:)=[];
A(:,:,:,n,:)=[];
A(:,:,:,:,n)=[];
问题:您能帮我将上面的代码推广到任何n
吗?我看不到如何进行.
Question: could you help me to generalise the code above to any n
? I cannot see how to proceed.
推荐答案
您可以使用包含多个元素的单元格索引矩阵.每个元素将被解释为新索引(
You can index your matrix with a cell containing multiple elements. Each element will be interpreted as a new index (more information here):
%Example 1: A(:,:,1:3,1:3,1:3}
%elements per dimension
n = 4;
%number of dimension
d = 5;
%random matrix
repdim = repmat({n},d,1)
A = rand(repdim{:});
%We want A(:,:,1:3,1:3,1:3}, so we create c = {1:3,1:3,1:3}
c = repmat({1:n-1},d-2,1);
%Get the new matrix
A = A(:,:,c{:});
%Example 2: A(1:3,1:3,:,:,:}
%elements per dimension
n = 4;
%number of dimension
d = 5;
%random matrix
repdim = repmat({n},d,1)
A = rand(repdim{:});
%We want A(1:3,1:3,:,:,:}, so we create c1 = {1:3,1:3} and c2 = {':',':',':'}
c1 = repmat({1:n-1},2,1);
c2 = repmat({':'},d-2,1); %thanks to @LuisMendo for the suggestion.
%Get the new matrix
A = A(c1{:},c2{:});
这篇关于在Matlab中通用化多维数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!