40 views (last 30 days)

Show older comments

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?

Thanking you in advance

Stephen Cobeldick
on 12 Apr 2021 at 11:11

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 = min(max(x,1),10) % this is all you need.

Rik
on 12 Apr 2021 at 10:08

Edited: Rik
on 12 Apr 2021 at 10:11

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 at 11:16

In that case you should use the code Stephen suggested.

If you have a piecewise function you can use the code I suggested.

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

Start Hunting!