matlab中for循环出错

时间:2015-02-23 19:45:55

标签: matlab for-loop

我在以下for循环中出错。我知道因为第一个for的结束值将被更改,并且Matlab在内部迭代中进行更改是不可接受的。但你知道如何克服它吗?顺便说一下,我使用了while,但根本没有帮助我。数据如下:

D = [
2.39484592826072e-05    286
4.94140791861196e-05    161
5.07906972800045e-05    163
0.000103133134300751    141
0.000142755898501384    136
0.000143741615840070    152
0.000188072960663613    177
0.000203545320971960    1
0.000269110781516704    296
0.000333161025069404    293
0.000351184122591795    167
0.000393661764751196    299
0.000469154814856272    173
0.000516662289403544    181
0.000537612407901054    156
0.000698464342131732    246
0.000848447859349023    66
0.000875283151707512    75
0.00102377583629824 68
0.00110034589129900 277
0.00110693756077989 129
0.00120680501123819 87
0.00151080017572355 78
0.00159156469379168 248
0.00190852817897233 270
0.00192106167039306 133
0.00224677708557380 258
0.00246430115488258 264
0.00288772180685041 255
0.00299392149856582 81
0.00315341807121748 242
0.00327625233716732 27
0.00362308575885149 124
0.00434568780796603 220
0.00443389247698617 239
0.00470947127244510 60
0.00474015278667278 23
0.00481651908877289 230
0.00487750364266560 53
0.00510342992049100 56
0.00513758569662983 228
0.00515453564704144 121
0.00515656244518627 232
0.00526922882200147 8
0.00547349131456174 50
0.00553337871530176 117
0.00569159206242299 18
0.00620144292620718 13
0.00630382865700000 119
0.00755647842280271 92
0.00983041839684126 40
0.00997057619578698 98
0.0102611966834032  44
0.0103337998140422  100
0.0105132461082006  37
0.0106952804631761  109
0.0107424055503829  208
0.0109630950142485  111
0.0115094667290339  105
0.0119529682389369  107];

ymin= D(:,1);
mean_value = 0.00773867192661190;
criteria = min(ymin);
kk = 1;
diff = 60;

以下是我希望更改size_D时出错的代码。

while criteria < mean_value
    if isempty(B)
        ind_crt = find(min(ymin));
        B(kk,:) = D(ind_crt,:);
        D(ind_crt,:) = [];
        kk = kk + 1;
    end
    criteria = min(min(D));
    size_D = size(D,1);
    for ii=1:size_D
        if D(ii,1) == criteria
            size_B = size(B,1);
            for jj = 1:size_B
                if abs(D(ii,2) - B(jj,2)) > diff
                    B(kk,:) = D(ii,:);
                    D(ii,:)= [];
                    kk = kk + 1;
                end
                size_D = size_D -1;
                criteria = min(min(D))
            end
        end
    end
end

更新

这是错误:

Attempted to access D(59,1); index out of bounds because
size(D)=[58,2].
Error in local_minima (line 50)
     if D(ii,1) == criteria 

1 个答案:

答案 0 :(得分:0)

loop替换为while循环,以便仅在验证条件ii<=size_D时才运行循环中的代码:

ii=0;
while ii<=size_D
  ii=ii+1;
  %loop code

而不是

for ii=1:size_D
  %loop code