简体   繁体   English

Matlab:在三维矩阵中放置零点

[英]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). 我正在使用for循环来计算xy平面子集(方形网格)上的电势。 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. 其中L是xy平面子集的长度。 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. 然而,我遇到的困难是我希望电势的z分量为零,我只是希望xy平面中的区域非零。 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 并尝试用零替换第二列中的那些,我通过键入(:,2)= 0来做,而matlab给了我

a =

     1     0     1
     1     0     1

I then tried to generalize this to a 3 dimensional matrix, but ran into some difficulty. 然后我尝试将其推广到3维矩阵,但遇到了一些困难。 Could someone help me? 有人能帮助我吗?

I assume you want to set the 2nd component of a 3 dimensional matrix to zero. 我假设您要将3维矩阵的第2个分量设置为零。

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. 您可以通过分配zeros(L,L,L)来合并第一步和第三步,但我认为这种方式更为明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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