简体   繁体   English

Matlab-在3D矩阵中查找2D矩阵值

[英]Matlab - Find 2d matrix values in 3d matrix

I have the following problem. 我有以下问题。 I have two matrices, one 2d matrix of size X,Y with a set of terrain heights taken from a DEM file and a 3d matrix of size X,Y,Z with Z height values from 0 to 5000 meters for each (X,Y) point. 我有两个矩阵,一个是XD尺寸的2d矩阵,具有从DEM文件中获取的一组地形高度,另一个是X,Y,Z尺寸的3d矩阵,每个Z高度值从0到5000米(X,Y )点。

I want to compare, for each (X,Y) point its DEM height with the column of Z height values and take the closest one. 我想将每个(X,Y)点的DEM高度与Z高度值的列进行比较,然后取最接近的一个。 For example: 例如:

dem(1,1) = 1850 %actual height of the terrain at point (1,1)
heights(1,1,:) = 0, 1000, 2000, 3000, 4000, 5000 %column of heights at point (1,1)

If I use the function "find" I get the following error: 如果使用函数“查找”,则会出现以下错误:

find(heights > dem, 1)
Error using  > 
Number of array dimensions must match for binary array op.

Is there any solution to this that doesn't require two for loops? 有什么解决方案不需要两个for循环吗?

Thank you very much in advance for your help! 预先非常感谢您的帮助!

You could reduce this to a loop over a single dimension using bsxfun : 您可以使用bsxfun将其减少到一个维度上的循环:

heights = rand(10, 10, 10);
dem = rand(5, 1);
bsxfun(@gt, heights(1, :, :), dem)

    [returns a 5x10x10 matrix]

You simply need to define your data as: 您只需要将数据定义为:

dem(1,1) = 1850;
heights(1,1,:) = [0; 1000; 2000; 3000; 4000; 5000];

Now, find(heights > dem, 1) yeilds 现在, find(heights > dem, 1)

ans =

     3

which is the expected result, the index of 2000 . 这是预期的结果,索引为2000

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

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