# Function using for loop

2 views (last 30 days)
Sayanta on 31 May 2012
Hi All,
I want to write a function using a for loop but the function will do the same functionality. The function is shown below
How can I do that any tips ?
Here is function
f unction [state1,state2] = stat(x)
% for previous state
if (x(1) <= 5)
state1 = 1;
end
if (x(1) > 5 && x(1) <= 10)
state1 = 2;
end
if (x(1) > 10 && x(1) <= 15)
state1 = 3;
end
if (x(1) > 15 && x(1) <= 20)
state1 = 4;
end
if (x(1) > 20 && x(1) <= 25)
state1 = 5;
end
if (x(1) > 25 && x(1) <= 30)
state1 = 6;
end
% for current state
if (x(2) <= 5)
state2 = 1;
end
if (x(2) > 5 && x(2) <= 10)
state2 = 2;
end
if (x(2) >10 && x(2) <= 15)
state2 = 3;
end
if (x(2) > 15 && x(2) <= 20)
state2 = 4;
end
if (x(2) > 20 && x(2) <= 25)
state2 = 5;
end
if (x(2) > 25 && x(2) <= 30)
state2 = 6;
end
Sayanta
Oleg Komarov on 31 May 2012
you can actually avoid a for loop and use histc()
Oleg Komarov on 31 May 2012
From my perspective this user has asked the same question for the 6th time, got an answer and did not interact with the contributors to get to the bottom of the problem. At this point I suggest to invest time with other users of the forum unless Sayanta starts giving some feedback.

Andrei Bobrov on 31 May 2012
x = unifrnd(3,36,20,1);
[state2,state2 ] = histc(x,[-inf,5:5:30] + eps(100));
or
k = [-30:5:-5 inf]
[j1,j1] = histc(-x,k )
n = numel(k)
state2 = rem(abs(j1-n),n)
Walter Roberson on 31 May 2012
As a usage note: andrei has used these mechanisms of adding eps() or negating the values involved, in order to compensate for the fact that histc() defines its bins as a <= x < b whereas your request was for a < x <= b . If your boundaries can be switched so that (for example) _exactly_ 25 is state 6 instead of state 5, then histc() can be used directly with no fiddling.

Geoff on 31 May 2012
There's a pattern here...
state1 = max( ceil(x(1) / 5), 1 );
state2 = max( ceil(x(2) / 5), 1 );
Just as a point on style... if you want to write a bunch of if statements for a continuous range, do this:
if x(2) <= 5
state2 = 1;
elseif x(2) <= 10
state2 = 2;
elseif x(2) <= 15
state2 = 3;
elseif % etc etc
% etc etc
else
state2 = NaN; % What happens if out of range?
end
Geoff on 31 May 2012
Note: you don't need the 'max' if x(?) is always greater than zero.