简体   繁体   中英

How to address all faces of a cube (3d array) in matlab?

I need to assign boundary values to a 3d box.

Assuming I have z = rand(L,M,N) , is there a better way to address all the faces of this box than processing all 6 faces individually, z(:,:,1) , z(:,:,end) , z(:,1,:) , z(:,end,:) , z(1,:,:) , z(end,:,:) ?

This is what I have right now:

L=3;M=4;N=5;
z = rand(L,M,N);
bv = 0;
z([1,end],:,:) = bv;
z(:,[1,end],:) = bv;
z(:,:,[1,end]) = bv;

I would like to be able to do something like z(indices) = bv .

Not sure if this is any better than your code, but here it goes:

%// Data
L = 3;
M = 4;
N = 5;
z = rand(L,M,N)
newValue = 0;

%// Let's go
indL = false(L, 1, 1);
indM = false(1, M, 1);
indN = false(1, 1, N);
indL([1 end]) = true;
indM([1 end]) = true;
indN([1 end]) = true;
ind = bsxfun(@or, bsxfun(@or, indL, indM), indN); %// linear index of all faces
z(ind) = newValue

Before:

z(:,:,1) =
    0.2653    0.7302    0.1078    0.8178
    0.8244    0.3439    0.9063    0.2607
    0.9827    0.5841    0.8797    0.5944
z(:,:,2) =
    0.0225    0.1615    0.0942    0.6959
    0.4253    0.1788    0.5985    0.6999
    0.3127    0.4229    0.4709    0.6385
z(:,:,3) =
    0.0336    0.5309    0.8200    0.5313
    0.0688    0.6544    0.7184    0.3251
    0.3196    0.4076    0.9686    0.1056
z(:,:,4) =
    0.6110    0.0908    0.2810    0.4574
    0.7788    0.2665    0.4401    0.8754
    0.4235    0.1537    0.5271    0.5181
z(:,:,5) =
    0.9436    0.2407    0.6718    0.2548
    0.6377    0.6761    0.6951    0.2240
    0.9577    0.2891    0.0680    0.6678

After:

z(:,:,1) =
     0     0     0     0
     0     0     0     0
     0     0     0     0
z(:,:,2) =
         0         0         0         0
         0    0.1788    0.5985         0
         0         0         0         0
z(:,:,3) =
         0         0         0         0
         0    0.6544    0.7184         0
         0         0         0         0
z(:,:,4) =
         0         0         0         0
         0    0.2665    0.4401         0
         0         0         0         0
z(:,:,5) =
     0     0     0     0
     0     0     0     0
     0     0     0     0

If you have the Image Processing toolbox, using padarray would work:

z = padarray(z(2:end-1,2:end-1,2:end-1), [1 1 1], bv);

This just takes the inner block of the cube and adds 1 copy of bv on all sides.

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