How to replace specific values to all values of a bin ?

I have a code that reads my data, and distribute them into bins: [0,2),[2,4),[4 6].
T=readtable('data.txt')
X=T(:,1)
Y=discretize(X,[ 0 2 4 6])
I would like to set specific value into each bin depending on its value.
I would like to set value 1.6 for values in first bin, value 3.8 for values in in second bin and value 5.7 for values in last bin.
I mean I would like to replace all values in first bin with 1.6, replace all the values of second bin with 3.8 and replace all the values of the third bin with 5.7
Could you please help me?

回答 (2 件)

Steven Lord
Steven Lord 2021 年 4 月 15 日

3 投票

Specify the values input argument in your discretize call.
x = 6*rand(10, 1);
d = discretize(x, 0:2:6, [1.6, 3.8, 5.7]);
results = table(x, d)
results = 10×2 table
x d _______ ___ 0.19796 1.6 3.9069 3.8 4.0021 5.7 0.85789 1.6 5.5115 5.7 5.0587 5.7 2.3297 3.8 5.465 5.7 0.73075 1.6 5.858 5.7
Image Analyst
Image Analyst 2021 年 4 月 15 日

0 投票

Did you try just a simple for loop with an If statement inside?

4 件のコメント

Ivan Mich
Ivan Mich 2021 年 4 月 15 日
編集済み: Ivan Mich 2021 年 4 月 15 日
I tried :
n=length(X)
for i=1:n
if 0<=X<2
X(i)=1.6
elseif 2<=X<4
X(i)== 3.8
else 4<=X<=6
X(i)==5.7
end
end
but no use...
Image Analyst
Image Analyst 2021 年 4 月 16 日
You can't do stuff like this 2<=X<4 in MATLAB. You need to break it up into two conditionals:
elseif (2 <= X) && (X < 4)
Fix the other lines of code as well, or just use Steve's solution.
Steven Lord
Steven Lord 2021 年 4 月 16 日
You can write 2 <= x < 4 in MATLAB. It's syntactically legal code. However it likely won't do what the poster wanted. It will return an array of true values the same size as x since 2 <= x is an array containing either true or false values (considered as 1 or 0 for relational operations respectively) and both 1 and 0 are less than 4.
If you were to type that in the Editor, Code Analyzer should underline that in orange, tell you that it probably doesn't do what you think it does, and offer the conditional split as a suggested fix.
Walter Roberson
Walter Roberson 2021 年 4 月 16 日
There is one place that 2 <= x < 4 works: inside piecewise() statements
syms x
piecewise(2 <= x < 4, 1, 4 <= x <= 5, 2, symtrue, 0)
ans = 

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

カテゴリ

ヘルプ センター および File ExchangeDescriptive Statistics and Insights についてさらに検索

質問済み:

2021 年 4 月 15 日

コメント済み:

2021 年 4 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by