Reputation: 675
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?
Upvotes: 0
Views: 185
Reputation: 36710
%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.
Upvotes: 1
Reputation: 7136
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
Upvotes: 1