将所有非零矩阵元素设置为 1(同时保持其他为 0)
我有一个网格定义为
[X, Y, Z] = meshgrid(-100:100, -100:100, 25); % z will have more values later
和 两个形状(在本例中为椭圆形):
x_offset_1 = 40;
x_offset_2 = -x_offset_1;
o1 = ((X-x_offset_1).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);
o2 = ((X-x_offset_2).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);
现在,我想找到椭圆形中所有非零的点。我尝试过
union = o1+o2;
,但由于我只是将它们相加,因此重叠区域的值为 2,而不是所需的 1。
如何将矩阵中的所有非零条目设置为 1,而不管它们之前的值如何?
(我尝试了 normalized_union = union./union;
,但最终我在所有 0 个元素中得到 NaN
,因为我除以零......)
I have a mesh grid defined as
[X, Y, Z] = meshgrid(-100:100, -100:100, 25); % z will have more values later
and two shapes (ovals, in this case):
x_offset_1 = 40;
x_offset_2 = -x_offset_1;
o1 = ((X-x_offset_1).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);
o2 = ((X-x_offset_2).^2./(2*Z).^2+Y.^2./Z.^2 <= 1);
Now, I want to find all points that are nonzero in either oval. I tried
union = o1+o2;
but since I simply add them, the overlapping region will have a value of 2 instead of the desired 1.
How can I set all nonzero entries in the matrix to 1, regardless of their previous value?
(I tried normalized_union = union./union;
, but then I end up with NaN
in all 0 elements because I'm dividing by zero...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的解决方案:
A=A~=0;
,其中A
是你的矩阵。这只是执行一个逻辑运算来检查每个元素是否为零。因此,如果元素非零,则返回
1
;如果元素为零,则返回0
。Simplest solution:
A=A~=0;
, whereA
is your matrix.This just performs a logical operation that checks if each element is zero. So it returns
1
if the element is non-zero and0
if it is zero.第一个建议:不要使用
union
作为变量名,因为这会隐藏内置函数联合
。我建议使用变量名称inEitherOval
来代替,因为它更具描述性......现在,您的一个选择是执行类似 abcd 建议,其中添加矩阵
o1
和o2
并使用 关系不等于运算符:同样,还有一些其他可能性使用逻辑
not
运算符或函数逻辑
:但是,最简洁的解决方案是应用逻辑
or
运算符直接连接到o1
和o2
:如果任一矩阵非零,则结果为 1,否则结果为零。
First suggestion: don't use
union
as a variable name, since that will shadow the built-in functionunion
. I'd suggest using the variable nameinEitherOval
instead since it's more descriptive...Now, one option you have is to do something like what abcd suggests in which you add your matrices
o1
ando2
and use the relational not equal to operator:A couple of other possibilities in the same vein use the logical
not
operator or the functionlogical
:However, the most succinct solution is to apply the logical
or
operator directly too1
ando2
:Which will result in a value of 1 where either matrix is non-zero and zero otherwise.
还有一个简单的解决方案,A=逻辑(A)
There is another simple solution, A=logical(A)