フィルターのクリア

Comparing my array to two variables

3 ビュー (過去 30 日間)
Matlabhelp
Matlabhelp 2016 年 9 月 29 日
コメント済み: Image Analyst 2020 年 8 月 25 日
Hello
I'm trying to compare my array values ( numerical ) to two variables. For example i would like any number in my array greater than 2 to be rounded to two, and any number less than 0 rounded to 0. I can't seem to find a simple expression to do this. So i would like to compare all numbers in the array to those two conditions and then round them to their respective closest number. How do i possible go about this?
  1 件のコメント
Image Analyst
Image Analyst 2020 年 8 月 25 日
Original question in case he deletes is like he's done with other posts:
Hello
I'm trying to compare my array values ( numerical ) to two variables. For example i would like any number in my array greater than 2 to be rounded to two, and any number less than 0 rounded to 0. I can't seem to find a simple expression to do this. So i would like to compare all numbers in the array to those two conditions and then round them to their respective closest number. How do i possible go about this?

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

採用された回答

KSSV
KSSV 2016 年 9 月 29 日
% Generate random data between -3 and 3
a = -3;
b = 3;
r = (b-a).*rand(100,1) + a;
r(r>2) = 2 ; % Change numbers greater then 2
r(r<0) = 0 ;% Change numbers less then 0
Read about find, round, ceil, floor.
  2 件のコメント
Matlabhelp
Matlabhelp 2016 年 9 月 29 日
Thank you for you help :)
Stephen23
Stephen23 2016 年 9 月 29 日
編集済み: Stephen23 2016 年 9 月 29 日
Note that this answer does not mention the simplest solution. See my answer.

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

その他の回答 (1 件)

Stephen23
Stephen23 2016 年 9 月 29 日
編集済み: Stephen23 2016 年 9 月 29 日
Simply use max and min, each with two arguments:
>> M = randi([-5,5],6)
M =
-5 3 5 -5 -5 -2
2 3 2 -4 -1 -1
-5 2 3 -4 0 -5
-5 -4 -1 -1 -1 5
0 2 -1 4 2 -4
-4 0 4 3 1 -4
>> min(2,max(0,M))
ans =
0 2 2 0 0 0
2 2 2 0 0 0
0 2 2 0 0 0
0 0 0 0 0 2
0 2 0 2 2 0
0 0 2 2 1 0

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by