Hi Amehri,
The following approach demonstrates an optimized version of the function:
By Incorporating ‘vectorization’ and ‘direct submatrix extraction’ significantly enhances the code's efficiency. Here is the explanation:
Vectorization Enhancement: The updated function utilizes vectorized operations through ‘arrayfun’ with 'UniformOutput' set to false. This approach efficiently transforms ‘NodesFree’ into exact row and column indices in one step, eliminating the need for nested loops and improving code efficiency.
Optimization via Direct Submatrix Extraction: This involves the direct utilization of pre-calculated indices, referred to as ‘actualIndicesKept’. With these indices, the function extracts the desired submatrix in one cohesive operation. This method not only simplifies the process but also leverages MATLAB's optimized matrix indexing and submatrix extraction functionalities to their fullest extent.
Following is the modified code using these strategies:
clear;
close all;
clc;
N = 400;
axis = 3;
A = rand(N*axis);
A = A - tril(A,-1) + triu(A,1)';
all_N = 1:N;
NodesRemove = [12; 32; 68; 95; 121; 145; 175; 182; 206; 242; 265; 287; 310; 335; 358; 389];
NodesKeep = setdiff(all_N, NodesRemove)';
tic
Ar = ReducedSystemParamOptimized(A, NodesKeep, axis);
toc
function Kr = ReducedSystemParamOptimized(K, NodesFree, Nbr_Axis)
% Pre-calculate the indices based on NodesFree and Nbr_Axis
indices = arrayfun(@(x) (x-1)*Nbr_Axis+1 : x*Nbr_Axis, NodesFree, 'UniformOutput', false);
indices = horzcat(indices{:}); % Convert cell array to a vector of indices
% Directly extract the submatrix based on calculated indices
Kr = K(indices, indices);
end
For better understanding of ‘vectorization’ you can refer to this document: