Selecting specific values from an array based on a defined condition

I have the following array:
d = [0,100,-100];
m = 300;
I want to select certain values of array d as follows:
d(0<=m+d<=300);
So i want to select all the d values where m+d is beween 0 and 300 with both ends included. The result should look like [0,-100] and 100 should be excluded since it is out the defined range. However, I am getting d to be [0,100,-100]. Please let me know where I went wrong.

 採用された回答

Fabio Freschi
Fabio Freschi 2019 年 9 月 25 日
編集済み: Fabio Freschi 2019 年 9 月 25 日

1 投票

d+m is not scalar: use a single & for logical AND
d(d+m >= 0 & d+m <= 300)

その他の回答 (1 件)

Johannes Fischer
Johannes Fischer 2019 年 9 月 25 日
編集済み: Johannes Fischer 2019 年 9 月 25 日

1 投票

Th logical expression
0 <= m+d <= 300
is not interpreted by Matlab as you think it is. It rather is interpreted as
(0 <= m+d) <= 300
where the expression in brackets results in logical 0 and 1 values which all are below 300, which in turn results in logical 1 at each position. What you want is a combination of both cases
d(0 <= m+d && m+d <= 300);

3 件のコメント

SB
SB 2019 年 9 月 25 日
I actually tried that. It gives me the following error:
Operands to the || and && operators must be convertible to logical scalar values.
Johannes Fischer
Johannes Fischer 2019 年 9 月 25 日
You are right, only one '&' is necessary
d(0 <= m+d & m+d <= 300);
SB
SB 2019 年 9 月 25 日
Thank you.

サインインしてコメントする。

カテゴリ

製品

リリース

R2017a

タグ

質問済み:

SB
2019 年 9 月 25 日

コメント済み:

SB
2019 年 9 月 25 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by