Vectorize embedded for and while loops

1 view (last 30 days)
Maggie Chong
Maggie Chong on 27 Jun 2023
Edited: Matt J on 27 Jun 2023
I am currently testing a small matrix D while I am in the early stages but later on, the matrix could be as large as 200 by 500 by 500. I am looking for a method to run my loops faster.
What is a smart way to vectorize this code?
Would it make sense to try and use a tall array for D instead?
for layer = 4:3:zi
% Loop through the rows
for ii = 1:size(D, 1)
% Loop through the columns
for j = 1:size(D, 2)
layercounter = layer;
while layercounter > 1
if D(ii ,j,layercounter-1) == 0
% make the deivation == 1
D(ii,j,layercounter-1)= D(ii ,j,layercounter);
D(ii,j,layercounter + 1) =D(ii,j,layercounter+2);
D(ii,j,layercounter+2) = 0;
end
layercounter = layercounter-1;
end
end

Answers (1)

ProblemSolver
ProblemSolver on 27 Jun 2023
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.

Categories

Find more on Get Started with Optimization Toolbox in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!