gpt4 book ai didi

matlab - 特定matlab代码的矢量化

转载 作者:行者123 更新时间:2023-12-01 13:36:23 25 4
gpt4 key购买 nike

我需要对以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com