简体   繁体   中英

Indices of boundary elements 3D matrix

I have a 65x76x100 3D-matrix, where each element contains a material type. I have assigned dynamics to each element, but the dynamics of the border elements (or boundary, or exterior, or perimeter, or how you want to call it) are incorrect and need to be removed. I require all the linear indices of the border elements, currently i do that like this (and it works):

    materials; % given 65x76x100 3D-matrix;
    [nxgrid, nygrid, nzgrid] = size(materials);
    n = nxgrid*nygrid*nzgrid;
    N2 = nxgrid*nygrid;
    borderIndices = zeros(n, 1); % initialize an oversized matrix that contains the border indices
        for l = 1:nzgrid % loop over zgrid
            for k = 1:nygrid % loop over ygrid
                for j = 1:nxgrid % loop over xgrid
                    if (j==1)||(j==nxgrid)||(k==1)||(k==nygrid)||(l==1)||(l==nzgrid)
                        i = (l-1)*N2 +(k-1)*nxgrid+j; % subscript to linear index
                        borderIndices(i) = i;
                    end
                end
            end
        end

Those nested for-loops seem a bit redundant to me though. Is there a more optimal/better/cleaner way to solve this?

You can do it easily as follows:

  1. Create a 3D array with true on the boundary and false otherwise, using or (|) with implicit expansion .
  2. Apply find with one output to get the linear indices of that.

indices = find([1; zeros(size(materials,1)-2,1); 1] | ...
               [1, zeros(1,size(materials,2)-2), 1] | ...
               reshape([1, zeros(1,size(materials,3)-2), 1], 1, 1, []));

If you want the result as in your code (with zeros between the indices):

indices_with_zeros(indices) = indices;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM