필터 지우기
필터 지우기

Vectorize embedded for and while loops

조회 수: 1 (최근 30일)
Maggie Chong
Maggie Chong 2023년 6월 27일
편집: Matt J 2023년 6월 27일
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

답변 (1개)

ProblemSolver
ProblemSolver 2023년 6월 27일
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.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by