简体   繁体   中英

Matlab: Placing Zeros In A Three Dimensional Matrix

I am using a for loop to calculate the electric potential on a subset of the xy-plane (a square grid). Here is the code:

L=2;

for i=1:L
    for j=1:L
        for k=1:L
        V(i,j,k)= -10;
        end 
    end
end

where L is the length of the subset of the xy-plane. The difficulty I am having, however, is that I want the z component of the electric potential to be zero, I just want to the region in the xy-plane to be nonzero. The reason why I am using three dimensions is because I am going to eventually introduce an object, which is at a different electric potential relative to the plane, that is above the plane.

What I tried was taking a simple two dimensional matrix:

a =

     1     1     1
     1     1     1

and tried replacing the ones in the second column with zeros, which I did by typing a(:,2)=0, and matlab gave me

a =

     1     0     1
     1     0     1

I then tried to generalize this to a 3 dimensional matrix, but ran into some difficulty. Could someone help me?

I assume you want to set the 2nd component of a 3 dimensional matrix to zero.

You can do this in the same way as you do for 2 dimensional case.

A = ones(3,3,3) % Never use For Loops the way you did for operating on matrices.
A(:,2,:) = 0
%allocate the matrix:
V=nan(L,L,L)
%fill z=0 with intended potential. Assign a scalar to have identical 
%values or a matrix to set individually
V(:,:,1)=-10
%set all other numbers to zero:
V(:,:,2:end)=0

You could merge the first and third step by allocating with zeros(L,L,L) , but I think this way it's more obvious.

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