通过逻辑索引将值分配给数组不起作用 [英] Assigning value to array by logical indexing doesn't work

查看:56
本文介绍了通过逻辑索引将值分配给数组不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Matlab中,我想将某个值替换为其他值.

In Matlab, I want to replace a certain value with some other value.

我知道我可以做到:

X(X==0) = -1 

如果我想将所有出现的0替换为1.

If I want to replace all occurrences of 0s to 1.

我有一个数组X,其中包含范围在0到9之间的数字.我想创建一个新数组Y,如果X(i)==一些给定的数字(例如5),则Y的第i个值为1. -1.所以我写了一个代码:

I have an array X that contains digits that range between 0 to 9. I want to create a new array Y where the ith value of Y is 1 if X(i) == some given digit, say 5, and otherwise -1. So I wrote a code:

Y = (X == 5); 
Y(Y==0) = -1; 

第一行工作正常.它将所有单元格从"5"投影到1,否则投影为0,因为这是逻辑运算.然后,如果它是0,我想将其替换为-1,但是第二行某种程度上使数组的所有值都变为1.有人知道为什么会发生这种情况吗?谢谢!

The first line works fine. It projects all cells with '5' to 1 otherwise 0 because it's a logic operation. Then if it's 0, I want to replace it with -1, but the second line somehow makes all value of the array to 1. Does anyone have insight why this would happen?? Thanks!

推荐答案

为什么您的方法不起作用确实有点好奇.原因是等式的左侧完全符合逻辑,右侧也被强制转换为

Why your approach was not working is indeed a little curios. The reason is that the left hand side of your equation is completely logical, the right hand side is casted logical as well and

logical(-1) = 1

因此:

Y = (X == 5)    %// Y is logical
Y(Y == 0) = -1  %// Y is logical, Y == 0 is logical, 
                %// -1 is casted to logical and logical(-1) = 1

因此,将您的第一个逻辑数组转换为double,它就可以工作.

So transform your first logical array to double, and it works.

Y = (X == 5)    %// Y is logical
Y = double(Y)   %// Y is double
Y(Y == 0) = -1  %// Y is double, Y == 0 is logical


示例:

X = randi(9,20,1);
Y = (X == 5)   
Y = double(Y)   
Y(Y == 0) = -1  
out = [X Y]


out =

     7    -1
     3    -1
     5     1
     7    -1
     9    -1
     9    -1
     5     1
     2    -1
     2    -1
     3    -1
     8    -1
     3    -1
     8    -1
     3    -1
     9    -1
     4    -1
     2    -1
     3    -1
     6    -1
     5     1

这篇关于通过逻辑索引将值分配给数组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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