Replace number if within 2 numbers and smaller than last number.

1 view (last 30 days)
Hello, I have a 45x2 array of numbers called 'ddindex'. The 1st row consist of starting number. 2nd row is the ending number.
Then, I have a list of numbers called 'indend2'. If indend2 is within these 2 numbers and is smaller than the ending number, replace indend2 with the ending number.
For example:
A = [1 15] B = [8, 42, 100...]
[20 36]
[37 50]
The output would be:
Output = [1 8]
[20 36]
[37 42]
As can be seen the 2nd row doesn't change because the number doesn't fall within the range of these values.
15 is replaced by 8, because 8 is smaller, and 50 is replaced by 42, because 42 is smaller and both numbers within these values.
How can I achieve this? Many thanks.

Accepted Answer

Walter Roberson
Walter Roberson on 9 Mar 2021
A = [1 15; 20 36; 37 50]
A = 3×2
1 15 20 36 37 50
B = [8, 42, 100]
B = 1×3
8 42 100
Select = @(M,idx) M(idx)
Select = function_handle with value:
@(M,idx)M(idx)
PW = @(cond,val1,val2) Select([val1,val2], [cond, ~cond])
PW = function_handle with value:
@(cond,val1,val2)Select([val1,val2],[cond,~cond])
cell2mat(arrayfun(@(row,b) [A(row,1), PW( b>=A(row,1)&b<=A(row,2), b, A(row,2)) ], (1:size(A,1)).', B(:), 'uniform', 0))
ans = 3×2
1 8 20 36 37 50
  2 Comments
Walter Roberson
Walter Roberson on 9 Mar 2021
A = [1 15; 20 36; 37 50]
A = 3×2
1 15 20 36 37 50
B = [8, 42, 100]
B = 1×3
8 42 100
cell2mat(arrayfun(@(row,b) [A(row,1), min(A(row,2), b./(b>=A(row,1)&b<=A(row,2)))], (1:size(A,1)).', B(:), 'uniform', 0))
ans = 3×2
1 8 20 36 37 50

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!