matlab - 特定matlab代码的矢量化

标签 matlab vectorization

我需要对以下 matlab 代码进行矢量化处理,现在对于较大的矩阵 A 和多重向量 m 来说速度很慢:

function cA = condenseM(A,m)
% condensation of full matrix A (MxM) to type matrix (MxT)
% m is vector of type multiplicities [m1, ...,mT], where 
% M = sum(m) 

% M,T
M = sum(m);
T = length(m);

% "0" + last item index over all types
blockTypeIndx = [0 cumsum(m)];

% condensed matrix generation
cA = zeros(M,T);
for i = 1:T
    if m(i) > 1
       cA(:,i) = max(A(:,blockTypeIndx(i)+1:blockTypeIndx(i+1)),[],2);
    else
       cA(:,i) = A(:,blockTypeIndx(i)+1:blockTypeIndx(i+1));
    end
end
end

这是矩阵 A (6x6) 的简单且足够通用的示例:

 A =

 0     3     3   |  1     1  |   6
 4     0     0   |  0     0  |   2
 0     0     0   |  5     0  |   0
 0     1     1   |  4     4  |   1
 2     0     0   |  0     0  |   5
 0     0     0   |  0     3  |   0
       m1=3          m2 = 2     m3=1

T=3 情况下的多重向量 m:

 m =
 3     2     1

压缩矩阵 cA 如下所示:

 cA = condenseM(A,m)
 cA = 

 3     1     6
 4     0     2
 0     5     0
 1     4     1
 2     0     5
 0     3     0

最佳答案

这是使用 cellfun 进行矢量化的可能代码,但在我的机器上它比你循环的要慢:

cb=cell2mat(cellfun(@(x) max(x,[],2),mat2cell(A,length(A),m),'Uniformoutput',false));

关于matlab - 特定matlab代码的矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063628/

相关文章:

r - 如何向量化用于排列的 for 循环?

algorithm - 在matlab中查找所有可能的排列/组合以等于特定的和

matlab - Matlab到openCV代码转换

string - Matlab - 如何逐个字母地比较两个字符串?

python - 不对称切片python

gcc - 循环中的 BB 太多,无法矢量化是什么意思?

matlab - 包含 MATLAB 图轴的框中缺少黑线

algorithm - 将重复出现的图像识别为更大的图像

MATLAB 无法加载由 Dymola 创建的 MAT 文件

python - 将零重新定位到多维 numpy 数组中最后一个维度的末尾