if a=[1 2 4 5 3 0 0 8 0]
how can i make the elements greater than or equal to 2 as 1 and smaller than two as 0.
so that it become like this:
[0 1 1 1 1 0 0 1 0]

 採用された回答

Arif Hoq
Arif Hoq 2022 年 2 月 12 日

0 投票

a=[1 2 4 5 3 0 0 8 0];
[idx]=find(a<2);
a(idx)=0;
out=a;
[idx2]=find(out>=2);
out(idx2)=1
out = 1×9
0 1 1 1 1 0 0 1 0

5 件のコメント

Catalytic
Catalytic 2022 年 2 月 12 日
編集済み: Catalytic 2022 年 2 月 12 日
This method does not work, so I don't know why it was accepted. a(1) is neither less than 0 nor greater tha or equal to 2. It should remain unchanged.
Arif Hoq
Arif Hoq 2022 年 2 月 12 日
a(1)=1 % 1 is < 2
It was asked to find >=2 would be 1 and <2 would be 0
DGM
DGM 2022 年 2 月 12 日
編集済み: DGM 2022 年 2 月 12 日
That might be how you read the question, but that's not what it says.
Granted, the OP's example output doesn't match their own requirement either.
ali hassan
ali hassan 2022 年 2 月 13 日
@DGM@Arif Hoq@Catalytic in haste, i made a mistake.
i have rectified it. i am sorry for it.
i intended to ask the same what @Arif Hoq replied. though in my question, i wrote zero instead of two but i got the concept which was required.
Matt J
Matt J 2022 年 2 月 13 日
編集済み: Matt J 2022 年 2 月 13 日
but i got the concept which was required.
Except that this solution still teaches the regrettably popular habit of using find() in situations where it is unnecessary.
a=[1 2 4 5 3 0 0 8 0];
out=a;
out(a<2)=0;
out(a>=2)=1
out = 1×9
0 1 1 1 1 0 0 1 0

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

その他の回答 (2 件)

DGM
DGM 2022 年 2 月 12 日
編集済み: DGM 2022 年 2 月 12 日

2 投票

I'm going to assume you're only dealing in integers here, otherwise the question arises whether values between 1 and 2 should really be preserved.
a = [1.5 1 2 4 5 3 0 0 8 0];
b = max(min(a,1),0)
b = 1×10
1 1 1 1 1 1 0 0 1 0
If values between 1 and 2 should be preserved, then:
c = max(a,0);
c(c>=2) = 1
c = 1×10
1.5000 1.0000 1.0000 1.0000 1.0000 1.0000 0 0 1.0000 0
Matt J
Matt J 2022 年 2 月 12 日
編集済み: Matt J 2022 年 2 月 13 日

0 投票

If a are always integers,
a = [1 2 4 5 3 0 0 8 0];
a=(a>=2)
a = 1×9 logical array
0 1 1 1 1 0 0 1 0

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

タグ

質問済み:

2022 年 2 月 12 日

編集済み:

2022 年 2 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by