如何调整MATLAB矩阵的大小

时间:2016-03-20 08:33:14

标签: matlab

如果我有矩阵size(mat)= X*Y*6

致电mat(:,:,1)=A

mat(:,:,2)=B依此类推

如何将垫子重新划分为X * Y * 12

其中

mat(:,:,1)=mat(:,:,2)= A
mat(:,:,3)=mat(:,:,4)=B

等等

2 个答案:

答案 0 :(得分:1)

您可以使用以下语法:

%defines input matrix (in your case it is already defined)
m = 500;
n = 400;
z = 6;
mat = rand(m,n,z); 

%initialize output matrix
newMat = zeros(m,n,z*2);

%assign old matrix values into the new matrix
newMat(:,:,1:2:end) = mat;
newMat(:,:,2:2:end) = mat;

答案 1 :(得分:1)

如果你有Matlab 2015a或更新版本,你可以使用repelem

N = 2; %// number of times to repeat
result = repelem(mat, 1, 1, N); %// repeat N times along 3rd dim

对于较旧的Matlab版本,您可以按如下方式手动执行:

N = 2; %// number of times to repeat
ind = ceil(1/N:1/N:size(mat,3)); %// build index with repetitions
result = mat(:,:,ind); %// apply index along desired dim

示例:

>> %// Data
>> mat = randi(9,2,4,2)
mat(:,:,1) =
     5     8     9     2
     7     3     1     5
mat(:,:,2) =
     5     7     1     1
     1     8     8     2

>> %// First approach
>> N = 2;
>> result = repelem(mat, 1, 1, N)
result(:,:,1) =
     5     8     9     2
     7     3     1     5
result(:,:,2) =
     5     8     9     2
     7     3     1     5
result(:,:,3) =
     5     7     1     1
     1     8     8     2
result(:,:,4) =
     5     7     1     1
     1     8     8     2

>> %// Second approach
>> N = 2;
>> ind = ceil(1/N:1/N:size(mat,3));
>> result = mat(:,:,ind)
result(:,:,1) =
     5     8     9     2
     7     3     1     5
result(:,:,2) =
     5     8     9     2
     7     3     1     5
result(:,:,3) =
     5     7     1     1
     1     8     8     2
result(:,:,4) =
     5     7     1     1
     1     8     8     2