3
votes

I need to vectorize the following matlab code, which is now slow for bigger matrices A and multiplicity vectors 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

This is simple and general enough example case for matrix 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

multiplicity vector m for T=3 case:

 m =
 3     2     1

The condensed matrix cA looks like:

 cA = condenseM(A,m)
 cA = 

 3     1     6
 4     0     2
 0     5     0
 1     4     1
 2     0     5
 0     3     0
1
are there any general limitations are characteristics you know? like in what range can length(m), max(m), min(m) or size(A) be? - Finn
A is MxM, where 30 < M < 100, 5 < length(m) < M, M = sum(m) - michalkvasnicka

1 Answers

0
votes

this is the a possible code for vectorization with cellfun, but on my machine it is slower than you loop:

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