Hello Maggie;
Not sure if this is what you are looking for? But to optimize the performance after looking at your snippit code, you can vectorize the operations using MATLAB's array operations. Here's an example:
layer = 4:3:zi;
% Loop through the layers in reverse order
for layerIndex = numel(layer):-1:2
% Find the indices where the previous layer is zero
zeroIndices = (D(:,:,layerIndex-1) == 0);
% Update the values in the previous, current, and next layers
D(:,:,layerIndex-1) = zeroIndices .* D(:,:,layerIndex) + ~zeroIndices .* D(:,:,layerIndex-1);
D(:,:,layerIndex+1) = zeroIndices .* D(:,:,layerIndex+2);
D(:,:,layerIndex+2) = zeroIndices .* 0;
end
Would it make sense to try and use a tall array for D instead?
To answer this question, to my experience using a tall array for 'D' may not necessarily lead to a faster execution of the code. Tall arrays are beneficial for handling large data sets that don't fit into memory, but they come with additional computational overhead. If you have sufficient memory to handle the size of matrix 'D', using a regular array should be efficient.
It's also worth considering if there are any other opportunities for optimization in your code. Analyzing the entire code structure and considering parallel computing techniques (such as parfor loops or MATLAB's Parallel Computing Toolbox) can potentially further enhance the performance of your code.
I hope this helps.