Improving the efficiency of repmat and function with inputs of different sizes

4 views (last 30 days)
I wrote a code that performs some calculation at each time step (Euler method). In the calculation I have groups of elements, which in principle can have different sizes. Some quantities need to be calculated per each element (X2_elements, Y_elements), other quantities in principle could be calculated only per each group (X, Z).
The code works correctly, but I identified two chockepoints that unreasonably reduce the computational speed. I believe the issue with both problems is that I am manipulating matrices and applying functions to them in an inefficient way.
Please find below the test code, where I highlighted the two Problems.
Additional notes:
-I do not really need the matrices X_elements and Z_matrices; I calculate them only to apply them together with Y_elements (which I do need) in myFunction.
-typically the number of elements in each group is 20 to 60 elements.
I'd like to find:
1. a more efficient way to calculate X_elements2, which at the moment uses repmat in a for-loop.
2. a more efficient to apply myFunction to the inputs, probably using the much smaller X and Z, instead of X_elements and Z_elements.
Thank you!
% Inputs
% nGroups: number of groups
% nElements: total number of elements
% nE: (1 x nGroups) vector indicating how many elements there are in each group
% elementToGroup: (1 x nElements) vector indicating to which group each element belongs
% Z: (1 x nGroups) vector with constant values (never updated during the calculation)
% fScalar: scalar parameter
% Initialization
X=zeros(nTime,nGroups);
X2=zeros(nTime,nGroups);
X_elements=zeros(nTime,nElements);
X_elements2=zeros(nTime,nElements);
Y_elements=zeros(nTime,nElements);
W_elements=zeros(nTime,nElements);
% Make cell structure containing indices of elements in each group
belongToG=cell(nGroups,1);
for g=1:nGroups
belongToG{g}=find(elementToGroup==g);
end
% Calculate once Z_elements
Z_elements=zeros(1,nElements);
for g=1:nGroups
Z_elements(belongToGroup{g})=Z(g);
end
% Main for-loop
for n=1:nTime
% do stuff... and a new row of the X, X2, Y_elements matrices are calculated
% Problem 1: Write values in all elements of each group
for g=1:nGroups
X_elements(n,belongToGroup{g})=repmat(X(n,g),1,nE(g)); % slow! :(
X_elements2(n,belongToGroup{g})=repmat(X2(n,g),1,nE(g)); % slow! :(
end
% do more stuff...
% Problem 2: Use the values in the new row of the matrices in a function
W_elements(n,:)=myFunction(X_elements(n,:),Y_elements(n,:),Z_elements,fScalar); % slow :(
% do more stuff...
end

Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!