matlab:switch the hundred-mark system to five-grade marking system
switch case problem in matlab
switch the hundred-mark system to five-grade marking system.function f=fjou(x)
switch x
case x>=90
f='5';
case x>=80&x<90
f='4';
case x>=70&x<80
f='3';
case x>=60&x<70
f='2';
otherwise
f='1';
end
开发者_JS百科if the parameter >60, the result is always "1", why?
You are using the switch statement like a series of if...elseif...elseif...else. The way switch works is that the argument to switch must match the case. Here is an example that does what you are looking for with a switch statement.
switch floor(x/10)
case 10,
f='5';
case 9,
f='5';
case 8,
f='4';
case 7,
f='3';
case 6,
f='2';
otherwise
f='1';
end
If I were going to do this in R, I'd just use the cut
function. I can't find an equivalent in MATLAB, but here's a cut down version. (No pun intended!)
function y = cut(x, breaks, right)
%CUT Divides the range of a vector into intervals.
%
% Y = CUT(X, BREAKS, RIGHT) divides X into intervals specified by
% BREAKS. Each interval is left open, right closed: (lo, hi].
%
% Y = CUT(X, BREAKS) divides X into intervals specified by
% BREAKS. Each interval is left closed, right open: [lo, hi).
%
% Examples:
%
% cut(1:10, [3 6 9])
% cut(1:10, [-Inf 3 6 9 Inf])
% cut(1:10, [-Inf 3 6 9 Inf], false)
%
% See also: The R function of the same name.
% $Author: rcotton $ $Date: 2011/04/13 15:14:40 $ $Revision: 0.1 $
if nargin < 3 || isempty(right)
right = true;
end
validateattributes(x, {'numeric'}, {});
y = NaN(size(x));
if right
leq = @gt;
ueq = @le;
else
leq = @ge;
ueq = @lt;
end
for i = 1:(length(breaks) - 1)
y(leq(x, breaks(i)) & ueq(x, breaks(i + 1))) = i;
end
end
Your use case is
cut(1:100, [-Inf 60 70 80 90 Inf], false)
Your problem is that in a SWITCH-CASE statement the switch expression (x
in your case) is compared to each case expression to find a match. Your case expressions all evaluate to logical results (i.e. 0 or 1), and when you compare x
to 0 or 1 you will never get a match for x
values of 60 or above. This is why the result of your switch statement is always the default otherwise
expression.
It should be noted that you can avoid the switch statement altogether with a simple vectorized solution using the function FIND:
f = find([-Inf 60 70 80 90] <= x,1,'last');
精彩评论