How to vectorize a for loop with an if condition inside

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 日

1 投票

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 件のコメント

AP
AP 2013 年 6 月 15 日
Wow. This is just amazing. Thanks a lot.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by