replace values in an array with certain numbers

I have an array (very long array) with values varying from 1 to 20 (with decimal values in between). What i want to do is the following:
if the values in my array are between 0 and 1, then replace with number 500;
if the values are between 1 and 2, then replace with 1000;
if the values are between 2 and 3, then replace with 1500;
..... and so on.
How could i do this, thanks in advance :)

 采纳的回答

You can get the logical indices by using:
idx = A >=0 & A< 1 ; % logical indices
A(idx) = 500 ; % repalces them
Follow the same with others.

2 个评论

This is likely the best way. It's probably possible to use a loop to avoid code getting too out of hand:
for val = 1:20
idx = (A >= val-1) && (A < val);
A(idx) = val*500;
end
both worked, thank you :)

请先登录,再进行评论。

更多回答(1 个)

x = 2*rand(10, 1);
edges = 0:2;
d = discretize(x, edges, [500, 1000]);
results = table(x, d, 'VariableNames', ["Raw data", "Discretized value"])
results = 10x2 table
Raw data Discretized value ________ _________________ 0.69853 500 1.5357 1000 0.18276 500 1.2076 1000 1.5088 1000 0.030049 500 0.049193 500 1.3234 1000 0.23645 500 1.2114 1000

类别

帮助中心File Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by