简体   繁体   中英

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.

I want to compare, for each (X,Y) point its DEM height with the column of Z height values and take the closest one. 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?

Thank you very much in advance for your help!

You could reduce this to a loop over a single dimension using 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

ans =

     3

which is the expected result, the index of 2000 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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