Help with if statement in a calculation loop

1 view (last 30 days)
Ivan Mich on 12 Apr 2021
Commented: Rik on 12 Apr 2021
Hello,
I have a problem with a code. I want to calculate some numbers but I want to "limit" my results via a loop.
I want values <1 to be =1, values with >10 to be 10 and the others to be calculated from this equation:
x= x*1.3+0.5. I wrote this code but it is not use
x= 5 + randn * 0.5
if x < 1
x == 1
elseif x > 10
x == 10
else x > 3
x == 1.3* x -0.75
end
Where is the problem?
Ivan Mich on 12 Apr 2021
I am sorry but running this code stil values up to 10 exist.
It is no use

Stephen Cobeldick on 12 Apr 2021
The simplest and most efficient solution is to use MIN and MAX:
x = 5 + randn(5,7)*1.5;
x = x*1.3 + 0.5
x = 5×7
7.6491 8.4519 8.8820 8.7385 9.8065 8.6945 8.5660 5.7131 13.1416 6.3650 9.1859 6.9860 9.4199 5.4750 8.8947 7.3018 6.4618 7.2714 9.2859 8.7553 5.7112 8.6327 5.6802 3.2153 9.5393 7.2815 7.1600 11.3087 6.1828 6.8579 9.3617 8.8780 4.6976 3.9478 7.3776
x = min(max(x,1),10) % this is all you need.
x = 5×7
7.6491 8.4519 8.8820 8.7385 9.8065 8.6945 8.5660 5.7131 10.0000 6.3650 9.1859 6.9860 9.4199 5.4750 8.8947 7.3018 6.4618 7.2714 9.2859 8.7553 5.7112 8.6327 5.6802 3.2153 9.5393 7.2815 7.1600 10.0000 6.1828 6.8579 9.3617 8.8780 4.6976 3.9478 7.3776

Rik on 12 Apr 2021
Edited: Rik on 12 Apr 2021
The problem is that you assume Matlab will process each element of x separately. Matlab will only do that if you use a loop.
An alternative is to use logical indexing to process x as an array.
L=x<1;
x(L)=1;
L=x>10;
x(L)=10;
L=x>3;
x(L)=1.3* x(L) -0.75;
Rik on 12 Apr 2021
In that case you should use the code Stephen suggested.
If you have a piecewise function you can use the code I suggested.