matlab:将百分制转换为五分制
matlab中的开关箱问题matlab:将百分制转换为五分制,matlab,Matlab,matlab中的开关箱问题 将百分制转换为五分制 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 函数f=fjou(x) 开关x 案例x
将百分制转换为五分制
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
函数f=fjou(x)
开关x
案例x>=90
f='5';
如果x>=80&x=70&x=60&x60,结果总是“1”,为什么?您使用switch语句就像一系列if…elseif…elseif…else。switch的工作方式是switch的参数必须与大小写匹配。下面是一个使用switch语句实现所需功能的示例
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如果我要在R中执行此操作,我只会使用cut
函数。我在MATLAB中找不到一个等价物,但这里有一个精简版。(没有双关语!)
您的问题是,在一个实例中,将开关表达式(x
)与每个实例表达式进行比较,以找到匹配项。您的案例表达式all计算结果(即0或1),当您将x
与0或1进行比较时,您将永远无法获得60或以上的x
值的匹配。这就是为什么switch语句的结果总是默认的,否则表达式
需要注意的是,您可以使用以下函数使用简单的矢量化解决方案完全避免switch语句:
f=find([-Inf 60 70 80 90]
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
cut(1:100, [-Inf 60 70 80 90 Inf], false)
f = find([-Inf 60 70 80 90] <= x,1,'last');