我们有四点,假设是订购的:
A = sort(randn(1,4))
我想在x
区间找到最大可能的数字0<x<1
,以便
A(1)<x<A(2) or A(3)<x<A(4)
一些例子:
A = [-1.4924 0.3004 1.6630 2.1204], x = 0.3004
A = [-0.4754 0.1353 0.6552 1.3873]; x = 1.0000
A = [-1.0213 -0.4521 -0.0905 0.1000]; x = 0.1000
A = [-1.8258 -0.5790 -0.4568 -0.1950]; x = 0.0000
A = [ 1.5000 2.0000 2.5000 3.0000]; x = 1.0000
您是否可以建议使用紧凑的代码来完成这项工作,而无需使用if
语句列出所有可能的方案?
答案 0 :(得分:0)
在没有if语句的情况下尝试这样做,我发现代码的可读性大大降低了。请注意,下面的代码中只有一个if语句,而其他几个if语句可以替代逻辑比较。
所有测试都通过,代码仍然非常简洁(没有注释的9行,并且遍历所有测试)。
A = [[-1.4924 0.3004 1.6630 2.1204];
[-0.4754 0.1353 0.6552 1.3873];
[-1.0213 -0.4521 -0.0905 0.1000];
[-1.8258 -0.5790 -0.4568 -0.1950];
[ 1.5000 2.0000 2.5000 3.0000]];
for i = 1:size(A,1)
% Reshape A so that each set of 2 entries are compared
Atmp = reshape(A(i,:),2,2);
% Find any valid entries
Valid = Atmp > 0 & Atmp < 1;
Ind_Valid = find(Valid == 1);
if (~isempty(Ind_Valid))
% If there are valid entries, return:
% max(A(ind),0) if the entry is the 1st of the pair
% max(A(ind),1) if the entry is the 2nd of the pair
max_Ind = max(Ind_Valid);
x = max(Atmp(max_Ind),mod(max_Ind,2))
else
% If there are no valid entries, return:
% 0 if max A < 0
% 1 if max A > 1
x = max(Atmp(:)) > 0
end
end
输出:
x =
0.3004
x =
1
x =
0.1000
x =
0
x =
1