||的操作数和&&运算符必须可转换为逻辑标量值 [英] Operands to the || and && operators must be convertible to logical scalar values

查看:909
本文介绍了||的操作数和&&运算符必须可转换为逻辑标量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,我正在寻找Matlab中的快速实现.我有一组值,可以这样说:

I have a simple problem that I'm looking for a fast implementation in Matlab. I have an array of values, let's say:

 a = floor(rand(5,5).*255)

然后我有一个大小相似的阈值数组,假设它是:

I then have a similarly sized threshold array, let's say it's:

a_thresh = floor(rand(5,5).*255)

对于a中的值,如果它们比a_thresh中的对应值小0.5x,我希望输出为0-类似地,对于1.2x,a_thresh中的值也应设置为零,:

For values within a if they are 0.5x smaller than the corresponding value in a_thresh I want the output to be 0 - similarly for 1.2x the value in a_thresh should also be set to zero, i.e.:

a(a < a_thresh.*0.4) = 0
a(a > a_thresh.*1.2) = 0

对于介于0.4x和0.5x之间以及1.0x和1.2x之间的值,我想要一个成比例的值;否则,如果介于0.5和1.0之间的值,我想使用不变的a值.我以为可以使用以下内容:

For values between 0.4x and 0.5x and 1.0x and 1.2x I want a proportional amount and else where between 0.5 and 1.0 I want to use the value of a unaltered. I thought I could use something like the following:

 a(a>= a_thresh .* 0.4 && a <a_thresh.* 0.5) = ((a - a_thresh.*0.4)/(a_thresh.*0.5 a_thresh.*0.4)) .* a;

但是,我看到一条错误消息:

However, I get an error that says:

||的运算符和&&操作必须可转换为逻辑标量值

Operands to || and && operations must be convertible to logical scalar values

有关如何解决此问题的任何建议?显然,我可以使用循环来做到这一点,这是微不足道的,但是我想让代码保持向量化.

Any advice on how to solve this? Obviously I could use loops to do this and it would be trivial, but I want to keep the code vectorized.

推荐答案

关于&&的事情是它只能在标量上运行,而&也可以在数组上运行.您应该将&&更改为&以使其正常工作(您可以在

The thing about && is that it can operate only on scalars, whereas & can operate on arrays as well. You should change the && to & to make it work (you can read more about it in this question).

更新:
关于注释中描述的第二个问题:左侧的元素数量有所不同,因为您使用的是索引(仅选择某些元素),而右侧则使用整个矩阵aa_thresh

Update:
Regarding your second problem described in a comment: the number of elements on the left is different because you're using indices (selecting only certain elements), and on the right you're working with the entire matrix a and a_thresh.

您需要在两面都使用索引,因此建议将其存储在变量中,然后将其用作数组下标,如下所示:

You need to use indices in both sides, so I suggest storing it in a variable and then use it as an array subscript, along these lines:

idx = (a >= a_thresh*0.4 & a < a_thresh*0.5);
a(idx) = ((a(idx)-a_thresh(idx)*0.4) ./ (a_thresh(idx)*0.5*a_thresh(idx)*0.4)) .* a(idx);

我不确定计算本身是否正确,因此请您检查一下.

I'm not sure if the calculation itself is correct, so I'll leave it to you to check.

这篇关于||的操作数和&amp;&amp;运算符必须可转换为逻辑标量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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