To improve the performance of your MATLAB script, try considering given optimization:
- Preallocation: Preallocating memory for structures and arrays can significantly enhance performance by reducing the need for MATLAB to dynamically resize data structures during execution.
- Vectorization: Replace loops with vectorized operations where possible.
- If a calculation is repeated within a loop but yields the same result each time, try computing it once before the loop and store it in a variable.
Below is the revised version of the code with above consideration:
tic
% Preallocate the Data2 structure array with the anticipated size
Data2(length(Data)/2) = struct('H0_SoundSpeed', [], 'H0_Points', [], 'R0_SectionName', [], ...
'R0_ScalingFactor', [], 'A2_SectionName', [], 'A2_AngleFirst', [], ...
'A2_ScalingFactor', [], 'I1_ScalingFactor', [], 'A2_AngleStep', [], ...
'R0_Range', [], 'A2_AngleStepTemp', [], 'I1_Intensity', []);
% Iterate over Data with a step of 2
for i = 1:2:length(Data)
dataRow = Data{i,1}; % Extract the data row once to avoid repeated indexing
% Extract and convert values
Data2(i).H0_SoundSpeed = typecast(uint32(hex2dec(dataRow(65:68))), 'single');
Data2(i).H0_Points = hex2dec(dataRow(135:136));
Data2(i).R0_SectionName = convertCharsToStrings(char(hex2dec(dataRow(137:138))));
Data2(i).R0_ScalingFactor = typecast(uint32(hex2dec(dataRow(141:144))), 'single');
Data2(i).A2_SectionName = convertCharsToStrings(char(hex2dec(dataRow(657:658))));
Data2(i).A2_AngleFirst = typecast(uint32(hex2dec(dataRow(661:664))), 'single');
Data2(i).A2_ScalingFactor = typecast(uint32(hex2dec(dataRow(665:668))), 'single');
Data2(i).I1_ScalingFactor = typecast(uint32(hex2dec(dataRow(1209:1212))), 'single');
% Preallocate arrays for the loop
numPoints = Data2(i).H0_Points;
Data2(i).A2_AngleStep = zeros(1, numPoints);
Data2(i).R0_Range = zeros(1, numPoints);
Data2(i).A2_AngleStepTemp = zeros(1, numPoints);
Data2(i).I1_Intensity = zeros(1, numPoints);
factor = Data2(i).H0_SoundSpeed * Data2(i).R0_ScalingFactor / 2;
angleFirst = Data2(i).A2_AngleFirst;
angleScale = Data2(i).A2_ScalingFactor;
intensityScale = Data2(i).I1_ScalingFactor;
% Calculate values in a loop
for j = 1:numPoints
rangeIndex = 2*j + 143;
angleStepIndex = 2*j + 691;
intensityIndex = 2*j + 1211;
Data2(i).R0_Range(j) = factor * hex2dec(dataRow(rangeIndex:rangeIndex+1));
Data2(i).A2_AngleStepTemp(j) = hex2dec(dataRow(angleStepIndex:angleStepIndex+1));
Data2(i).A2_AngleStep(j) = angleFirst + sum(Data2(i).A2_AngleStepTemp(1:j)) * angleScale;
Data2(i).I1_Intensity(j) = intensityScale * hex2dec(dataRow(intensityIndex:intensityIndex+1));
end
end
% Remove temporary field
Data2 = rmfield(Data2, 'A2_AngleStepTemp');
toc
Hope this Helps!