说我有模拟:
for i = 1:100;
s1 = rand(1)*0.1+0.1;
s2 = rand(1)*0.2+0.2;
s3 = rand(1)*0.3+0.3;
s4 = s1+s2*s3;
sim_results(i,:) = [s1 s2 s3 s4];
end
我现在想要一个单独的矩阵,只有当s4
符合某些标准时才会显示结果:
x = sim_results(:,4)>0.1 && sim_results(:,4)<0.4
(这不起作用......)
答案 0 :(得分:2)
由于您编入sim_results
的方式,这不起作用。此外,您可能希望查看逻辑运算符上的this链接,因为在您的情况下,您可能希望使用&
而不是短路&&
。也就是说,如果你考虑这个表达式:
expr1 && expr2
如果expr2
为false,则不会评估expr1
。底线是,使用您使用的代码,您可能会得到错误Operands to the || and && operators must be convertible to logical scalar values.
,因为&&
运算符仅使用标量逻辑条件运行,即当您可以将条件汇总为真或假时,比较数组或矩阵时不是这种情况。
所以回到你的问题,我建议你做以下任何一种:
解决方案1:矢量化代码
这里您不需要循环,因为您使用的每个操作都可以进行矢量化:
s1 = rand(100,1)*.1+.1;
s2 = rand(100,1)*.2+.2;
s3 = rand(100,1)*.3+.3;
s4 = s1 + s2.*s3;
sim_results = [s1 s2 s3 s4];
x = find(s4 > .1 & s4 < 0.4) %// Get row indices for your condition
Result = sim_results(x,:)
5行的简单示例(我使用条件s4&gt; 0.4&amp; s4&lt; 0.4):
sim_results =
0.1760 0.3303 0.4169 0.3137
0.1584 0.3487 0.5326 0.3441
0.1403 0.2604 0.3538 0.2324
0.1510 0.2179 0.3328 0.2235
0.1496 0.3652 0.5715 0.3583
x =
1
2
5
Result =
0.1760 0.3303 0.4169 0.3137
0.1584 0.3487 0.5326 0.3441
0.1496 0.3652 0.5715 0.3583
解决方案2:使用临时变量
您可以在此处将变量分配给sim_results
的第4列,并按上述方式应用运算符:
for i = 1:100;
s1 = rand(1)*0.1+0.1;
s2 = rand(1)*0.2+0.2;
s3 = rand(1)*0.3+0.3;
s4 = s1+s2*s3;
sim_results(i,:) = [s1 s2 s3 s4];
end
TempVar = sim_results(:,4);
x1 = find(TempVar > .1 & TempVar < 0.4)
Result = sim_results(x1,:)
希望有所帮助!