How to vectorize a for loop with an if condition inside

조회 수: 3 (최근 30일)
AP
AP 2013년 6월 14일
Dear All,
How can I vectorize the following loop? Basically, I have a structured grid in whose node ids are stored in a array called nodes_id. A hexagonal element is constructed by using 8 nodes. I am trying to find the lower left nodes of each element. This allows me to obtain the nodes which belong to a certain element. The array nodes_in_elements holds this information for me. The following snippet works perfectly for me. In this example, I have 27 nodes which construct 8 hexagonal elements. I don't know how to vectorize it because it has an if-condition as well as a command, ind2sub, inside the loop.
Nx = 3; Ny = 3; Nz = 3;
number_of_elements = (Nx-1)*(Ny-1)*(Nz-1);
lower_left_nodes = zeros(1,number_of_elements); % initialization
nodes_in_elements= zeros(number_of_elements,8); % initialization
counter = 1;
nodes_id = 1:Nx*Ny*Nz;
for i=nodes_id % loop through all node Ids
[I, J, K] = ind2sub([Nx, Ny, Nz],i);
if ( I<Nx && J<Ny && K<Nz )
lower_left_nodes(counter) = i;
nodes_in_elements(counter,:) = [ i i+1 i+4 i+3 i+9 i+10 i+13 i+12];
counter = counter+1;
end
end
Could someone help me in vectorizing the above code? Thanks.

채택된 답변

Roger Stafford
Roger Stafford 2013년 6월 15일
L = reshape((1:Nx*Ny*Nz),Nx,Ny,Nz);
L = reshape(L(1:end-1,1:end-1,1:end-1),[],1);
N = [L,L+1,L+4,L+3,L+9,L+10,L+13,L+12];
L = L';
Where L stands for 'lower_left_nodes' and N for 'nodes_in_elements'.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Lighting, Transparency, and Shading에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by