如何跳过循环内的错误并让循环继续

时间:2014-02-23 12:20:07

标签: matlab

以下是我的完整代码:(大部分内容对我所要求的内容没有用,但我只是将整个代码放入上下文中,导致我麻烦的代码部分即将结束)

clc
clear


P = xlsread('b3.xlsx', 'P');
d = xlsread('b3.xlsx', 'd');
CM = xlsread('b3.xlsx', 'Cov');


Original_PD = P;                         %Store original PD
LM_rows = size(P,1)+1;                   %Expected LM rows
LM_columns = size(P,2);                  %Expected LM columns
LM_FINAL = zeros(LM_rows,LM_columns);    %Dimensions of LM_FINAL


% Start of the outside loop

for k = 1:size(P,2)

P = Original_PD(:,k);

interval = cell(size(P,1)+2,1);

for i = 1:size(P,1)
    interval{i,1} = NaN(size(P,1),2);
    interval{i,1}(:,1) = -Inf;
    interval{i,1}(:,2) = d;

    interval{i,1}(i,1) = d(i,1);
    interval{i,1}(i,2) = Inf;
end
interval{i+1,1} = [-Inf*ones(size(P,1),1) d];
interval{i+2,1} = [d Inf*ones(size(P,1),1)];

c = NaN(size(interval,1),1);
for i = 1:size(c,1)
    c(i,1) = mvncdf(interval{i,1}(:,1),interval{i,1}(:,2),0,CM);
end

c0 = c(size(P,1)+1,1);
f = c(size(P,1)+2,1);
c = c(1:size(P,1),:);
b0 = exp(1);
b = exp(1)*P;

syms x;

eqn = f*x;
for i = 1:size(P,1)
    eqn = eqn*(c0/c(i,1)*x + (b(i,1)-b0)/c(i,1));
end

eqn = c0*x^(size(P,1)+1) + eqn - b0*x^size(P,1);

x0 = solve(eqn);


for i = 1:size(x0)
    id(i,1) = isreal(x0(i,1));
end

x0 = x0(id,:);
x0 = x0(x0 > 0,:);

clear x;

for i = 1:size(P,1)
    x(i,:) = (b(i,1) - b0)./(c(i,1)*x0) + c0/c(i,1);
end


x = [x0'; x];
x = double(x);
x = x(:,sum(x <= 0,1) == 0)


lamda = -log(x);
LM_FINAL(:,k) = lamda;


end
% end of the outside loop

上述循环的重要部分是结束:

x = x(:,sum(x <= 0,1) == 0)

有时不满足此条件,因此变量x为空,这意味着LM_FINAL(:,k) = lamda也为空。发生这种情况时,我收到错误:

x =

   Empty matrix: 43-by-0

    Improper assignment with rectangular empty matrix.

    Error in Solution (line 75)
    LM_FINAL(:,k) = lamda;

如何跳过此错误,以便LM_FINAL的列保持为空,但循环继续(以便其余的LM_FINAL列填充)而不是终止?

1 个答案:

答案 0 :(得分:1)

您可以使用try and catch词组显式处理循环内部(或代码中的其他位置)的错误。