Function using for loop
1 次查看(过去 30 天)
显示 更早的评论
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
Many Thanks in advance
Sayanta
2 个评论
Oleg Komarov
2012-5-31
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.
回答(2 个)
Andrei Bobrov
2012-5-31
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)
1 个评论
Walter Roberson
2012-5-31
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
2012-5-31
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
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!