检查3D矩阵Matlab的元素明智等式 [英] Check element wise equality of a 3D matrix Matlab

查看:99
本文介绍了检查3D矩阵Matlab的元素明智等式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3D矩阵,例如. A(10x5x8).我需要从中获取尺寸为10x5的2D矩阵(布尔).

I have a 3D matrix say for eg. A(10x5x8). I need to get a 2D matrix (Boolean) out of it of size 10x5.

True,如果其基本3维值都相同.即Result(1,1) = 1,如果A(1,1,1) == A(1,1,2) == A(1,1,3)等.

True if its elemental 3 Dimensional values are all same. i.e. Result(1,1) = 1 if A(1,1,1) == A(1,1,2) == A(1,1,3) etc..

False,如果至少一个不同.

False if at least one is different.

我希望有一种快速有效的矢量化方法.

I expect a vectored approach which is fast and efficient.

示例输入:

A(:,:,1) = 1 2
           2 2
A(:,:,2) = 1 1
           2 3

预期输出:

Result = 1 0
         1 0

推荐答案

使用 bsxfun eq函数,并使用第一个切片作为第一个输入,并与其他切片比较作为第二个输入.允许第一个输入在多个片段上进行广播.

Use bsxfun with the eq function and use the first slice as the first input and compare with the other slices for the second input. Allow the first input to broadcast itself over the multiple slices.

完成此操作后,请使用 all 并检查第三维:

Once you do that, use all and check the third dimension:

ind1 = bsxfun(@eq, A(:,:,1), A(:,:,2:end);
ind2 = all(ind1, 3);

上面的逻辑很简单.代码的第一行的工作方式是,您将创建一个临时矩阵,该矩阵将使用A的第一个切片,并使其与A中的切片一样复制自身,而没有第一个切片.完成此操作后,您将使用此临时矩阵和其他切片进行逐个元素相等.如果您有一个全部相等的3D列,则将第一个切片中的一个元素与对应于同一3D列的每个单个值进行比较.如果它们彼此相等,那么您将获得一个全为逻辑1的3D列.因此,要使3D列彼此相等,则所有值都应为1,这就是使用all的原因-检查3D列中的所有值是否均等于1. 3D列是合乎逻辑的1,我们已经符合您的条件.

The logic behind the above is very simple. How the first line of code works is that you would create a temporary matrix that would take the first slice of A and let it duplicate itself for as many slices as you have in A, without the first slice. Once you do this, you would do an element-by-element equality with this temporary matrix and the other slices. If you had a 3D column that was all equal, the one element from the first slice would be compared with every single value that corresponds to the same 3D column. Should they all equal to each other, then you would get a 3D column of all logical 1s. Therefore, to have a 3D column that is all equal to each other, all of the values should be 1, which is why all is used - to check if all values in a 3D column are equal to 1. Should all of the 3D column be a logical 1, we have matched your criteria.

>> A1 = [1 2; 2 2];
>> A2 = [1 1; 2 3];
>> A3 = [1 3; 2 4];
>> A4 = [1 5; 2 6];
>> A = cat(3, A1, A2, A3, A4);    
>> ind1 = bsxfun(@eq, A(:,:,1), A(:,:,2:end);
>> ind2 = all(ind1, 3)

ind2 =

     1     0
     1     0

我制作了一个包含4个切片的矩阵,其中左上角和左下角的3D列均具有相同的值.一旦您在文章开头阅读了所有代码,我们就会得到您所期望的.

I made a matrix of 4 slices where the 3D column at the top left corner and the bottom left corner have all of the same values. Once you run through the code at the beginning of the post, we get what you expect.

这篇关于检查3D矩阵Matlab的元素明智等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆