MATLAB中的按元素矩阵复制 [英] Element-wise Matrix Replication in MATLAB

查看:713
本文介绍了MATLAB中的按元素矩阵复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3维矩阵.我想将尺寸为8x2x9的矩阵复制到向量说[3, 2, 1, 1, 5, 4, 2, 2, 1]的第三维中指定的次数,以使结果矩阵的尺寸为8x2x21.对于矩阵,是否有任何内置的MATLAB函数(我正在运行2014a版本)来完成此操作,类似于更新的repelem函数?

I have a 3 dimensional matrix. I want to replicate the matrix of size 8x2x9 to a specified number of times in the third dimension given by a vector say [3, 2, 1, 1, 5, 4, 2, 2, 1] so that the resultant matrix is of size 8x2x21. Is there any built-in MATLAB function (I'm running version 2014a) to do this similar to the newer repelem function, for matrices?

我需要的一个简单示例:

A simple example of what I need:

% Input:
A(:,:,1) = [1 2; 1 2];
A(:,:,2) = [2 3; 2 3];

% Function call:
A = callingfunction(A, 1, 1, [1 2]);

% Output:
A(:,:,1) = [1 2; 1 2];
A(:,:,2) = [2 3; 2 3];
A(:,:,3) = [2 3; 2 3];

推荐答案

对于R2015a和更高版本...

根据 repelem 的文档(首次引入在版本R2015a中),它也可以在矩阵上运行.我相信以下代码可以完成您想要的(我无法测试它,因为我有一个较旧的版本):

For R2015a and newer...

According to the documentation for repelem (first introduced in version R2015a), it can operate on matrices as well. I believe the following code should accomplish what you want (I can't test it because I have an older version):

newMat = repelem(mat, 1, 1, [3 2 1 1 5 4 2 2 1]);

对于R2015a之前的版本...

您可以使用此问题中的一种方法将索引复制到第三维中,然后只需对您的索引进行索引矩阵.例如(适应 Divakar的解决方案):

For pre-R2015a versions...

You can use one of the approaches from this question to replicate an index into the third dimension, then simply index your matrix with that. For example (adapting Divakar's solution):

vals = 1:size(mat, 3);
clens = cumsum([3 2 1 1 5 4 2 2 1]);
index = zeros(1, clens(end));
index([1 clens(1:end-1)+1]) = diff([0 vals]);
newMat = mat(:, :, cumsum(index));

然后您可以将其概括为一个函数,以像repelem那样在多个维度上进行操作:

You can then generalize this into a function to operate on multiple dimensions like repelem does:

function A = my_repelem(A, varargin)

  index = cell(1, nargin-1);
  for iDim = 1:nargin-1
    lens = varargin{iDim};
    if isscalar(lens)
      if (lens == 1)
        index{iDim} = ':';
        continue
      else
        lens = repmat(lens, 1, size(A, iDim));
      end
    end
    vals = 1:size(A, iDim);
    clens = cumsum(lens);
    index{iDim} = zeros(1, clens(end));
    index{iDim}([1 clens(1:end-1)+1]) = diff([0 vals]);
    index{iDim} = cumsum(index{iDim});
  end
  A = A(index{:});

end

对于示例数据,您将像这样使用它:

And for your sample data, you would use it like so:

>> A(:,:,1) = [1 2; 1 2];
>> A(:,:,2) = [2 3; 2 3];
>> A = my_repelem(A, 1, 1, [1 2])

A(:,:,1) =

     1     2
     1     2

A(:,:,2) =

     2     3
     2     3

A(:,:,3) =

     2     3
     2     3

这篇关于MATLAB中的按元素矩阵复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆