How to vectorize a for loop with an if condition inside
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Graphics Object Properties 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!