基于整数值将矩阵拆分为单独的二进制矩阵-MATLAB [英] split matrix into separate binary matrices based on integer value - matlab

查看:82
本文介绍了基于整数值将矩阵拆分为单独的二进制矩阵-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

m  = randi([1 4],4,4)

我想为每个唯一的整数创建单独的二进制矩阵:

I'd like to create separate binary matrices for each unique integer:

mm{1} = m==1
mm{2} = m==2
mm{3} = m==3
mm{4} = m==4

使用四个不同的整数,上面的方法就可以了,但是我的原始矩阵具有如此多的唯一值,我想知道是否有一种更自动化的方法来实现这一点.

With four different integers the above is fine, but my original matrix has so many unique values, I wonder if there is a more automated way of doing this.

推荐答案

一个选项是创建3D 逻辑矩阵,其中每个2D平面都是所需的二进制矩阵之一.假设您要测试从1到m中找到的最大值的所有整数,可以使用 bsxfun 隐式扩展(在R2016b版本或MATLAB的更高版本中):

One option is to create a 3D logical matrix where each 2D plane is one of your desired binary matrices. Assuming you want to test for all integers from 1 to the maximum value found in m, you can do this using either bsxfun or implicit expansion (in versions R2016b or newer of MATLAB):

N = max(m(:));

mm = bsxfun(@eq, m, reshape(1:N, [1 1 N]));
% or
mm = (m == reshape(1:N, [1 1 N]));  % Implicit expansion

现在,如果您想要m = 2的二进制矩阵,只需索引到mm:

And now if you want the binary matrix for m = 2, you simply index into mm:

mat = mm(:, :, 2);

这篇关于基于整数值将矩阵拆分为单独的二进制矩阵-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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