0
votes

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?

2
I don't understand what output you are expecting.Daniel
@Daniel I am calculating the electric potential at points in space, but I want the z-component to be zero.Mack
There is no "z-component" in a 3d-matrix. A point (x,y,z) has a z-component.Daniel
@Daniel But I using the elements of the matrices as the electric potential at some point (x,y,z), and I want it be zero everywhere that is not in the xy-plane, and nonzero in the xy-plane.Mack
Okay, I think now I got how you are interpreting a 3D-Matrix. In your interpretation, it's a regular grid of points where M(1,1,1) is the zero point. Indexing starts at 1, that makes it a bit tricky.Daniel

2 Answers

1
votes

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
1
votes
%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.