MATLAB Answers

How to vectorize a for loop with an if condition inside

27 views (last 30 days)
AP on 14 Jun 2013
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;
Could someone help me in vectorizing the above code? Thanks.


Sign in to comment.

Accepted Answer

Roger Stafford
Roger Stafford on 15 Jun 2013
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'.

  1 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Translated by