add=0; for k1=1:1:8 if k1==1;m=fault1;end if k1==2;m=fault2;end if k1==3;m=fault3;end if k1==4;m=fault4;end if k1==5;m=fault5;end if k1==6;m=fault6;end if k1==7;m=fault7;end if k1==8;m=fault8;end for k2=k1+1:1:9 if k2==2;n=fault2;end if k2==3;n=fault3;end if k2==4;n=fault4;end if k2==5;n=fault5;end if k2==6;n=fault6;end if k2==7;n=fault7;end if k2==8;n=fault8;end if k2==9;n=fault9;end % m=fault1; % n=fault2; a=sum(m .* n); b=sqrt(sum(m .^2)*sum(n .^2)); R=a/b; E=(1-R^2)*sum(m .^2); add=add+E; end end average=add/36; disp(E);上述代码报错:数组索引必须为正整数或逻辑值。如何更改
时间: 2023-08-29 10:04:55 浏览: 76
这个错误是因为在if语句中,当条件不满足时,变量`m`和`n`没有被赋值。您可以在循环之前为这两个变量设置默认值,以避免出现此错误。以下是修改后的代码示例:
```matlab
add = 0;
% 设置默认值
m = fault1;
n = fault2;
for k1 = 1:1:8
if k1 == 1; m = fault1; end
if k1 == 2; m = fault2; end
if k1 == 3; m = fault3; end
if k1 == 4; m = fault4; end
if k1 == 5; m = fault5; end
if k1 == 6; m = fault6; end
if k1 == 7; m = fault7; end
if k1 == 8; m = fault8; end
for k2 = k1+1:1:9
if k2 == 2; n = fault2; end
if k2 == 3; n = fault3; end
if k2 == 4; n = fault4; end
if k2 == 5; n = fault5; end
if k2 == 6; n = fault6; end
if k2 == 7; n = fault7; end
if k2 == 8; n = fault8; end
if k2 == 9; n = fault9; end
a = sum(m .* n);
b = sqrt(sum(m .^2) * sum(n .^2));
R = a / b;
E = (1 - R^2) * sum(m .^ 2);
add = add + E;
end
end
average = add / 36;
disp(E);
```
这样修改后,代码应该能够正常运行并显示结果,而不会再报错。
阅读全文