首页 > 解决方案 > 为什么这段代码不返回我的 3D 数组中元素的索引?

问题描述

我有一个调用的 3d 数组V_exact,其中有一个我想找到的特定值,由 给出Potential(0.001,-0.0008,0.0035),其中Potential是一些函数,它接受 3 个坐标并转换一个值。这是我尝试使用的代码:

%create axis vectors
x=-4*10^-3:0.1*10^-3:4*10^-3;
y=-4*10^-3:0.1*10^-3:4*10^-3;
z=-4*10^-3:0.1*10^-3:4*10^-3;
%create 3d grid of points
[X,Y,Z]=meshgrid(x,y,z);
%3d grid of potentials
V_exact=Potential(X,Y,Z);
%Potential that we want to find the location of in V_exact 
V_p=Potential(0.001,-0.0008,0.0035);
%code to find location, first find the linear indice of V_p in V_exact
linear=find(V_exact==V_p)
%Change linear indice into a coordinate
[i,j,k]=ind2sub(size(V_exact),linear);

这里的问题是它[i,j,k]具有多个值,而我只是希望它给我元素的索引,V_exact其中等于Potential(Potential(0.001,-0.0008,0.0035). 另一个问题是,即使有许多具有该值的元素,如果我运行V_exact(i,j,k),我最终不会得到所有点都等于V_p,只有一些是。谁能理解我做错了什么,或者代码输出了什么?

Potential功能代码:

function [outputArg1] = Potential(x,y,z)
k=8987551788.7;
q1=1;
q2=-1;
outputArg1 = (k*q1)./sqrt(x.^2+(y-1*10^-3).^2+z.^2) + (k*q2)./sqrt(x.^2+(y+1*10^-3).^2+z.^2);
end

标签: matlab

解决方案


由于您的功能电位是非内射的,因此不同的输入可以为您提供相同的输出。这就是为什么您的线性索引中有多个值linear

由于我们需要 4D 图,因此很难可视化您的函数的结果。但是我们可以固定一个坐标来仅在 3D 中可视化一个“层”。例如我们选择那个z = z(50)

surf(X(:,:,50),Y(:,:,50),V_exact(:,:,50),'EdgeColor','none')
hold on
contour3(X(:,:,50),Y(:,:,50),V_exact(:,:,50),'red')

在此处输入图像描述

所有等值线(红色)都具有相同的、非唯一的V_exact值。

现在要访问V_exact您需要使用线性索引,请阅读有关数组索引的文档!所以 的所有值都V_exact(linear)将等于V_p


推荐阅读