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 :)

 Accepted Answer

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 Comments

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 :)

Sign in to comment.

More Answers (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

Categories

Asked:

on 14 Dec 2020

Commented:

on 16 Dec 2020

Community Treasure Hunt

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

Start Hunting!