开发者

unexpected results of a function in matlab

Normally this function should give me the values ​​1, 2, 3 or 4. but when I use it, I get 0, 1 or 2. Could you help me to know where is the problem:

function Vecteur_retour = var_Test(Test)

AA = Test;

var_Test = zeros(1,2000);

for i=3:1:2000  
     if AA(i)<=AA(i-1) && AA(i-1)<=AA(i-2)  
     var_Test(i)=1;  
     else   
     if AA(i)<=AA(i-1) && AA(i-1)>AA(i-2)  
     var_Test(i)=2;  
     if AA(i)>AA(i-1) && AA(i-1)<=AA(i-2)  
     var_Test(i)=3;  
     else  
     if AA(i)>AA(i-1) &开发者_运维知识库amp;& AA(i-1)>AA(i-2)  
     var_Test(i)=4;  


     end   
     end   
     end  
     end  


end  


Vecteur_retour = var_Test;


Vector comparisons will be much faster:

var_Test = ones(1,2000);

delta_Test = diff(Test);
var_Test([0 0 delta_Test(1:end-1)] > 0) = 2;
var_Test([0 delta_Test] > 0) = var_Test([0 delta_Test] > 0) + 2;
var_Test(1:2) = 0;


Probably because you never reach the cases var_Test(i) = 3 or var_Test(i) = 4.

You have a problem with your if and end blocks. The way you have it, case 3 is only reached if case 2 is hit first, but these are contradictory.

You want code more like.

 function Vecteur_retour = var_Test(Test)  

 AA = Test;  
 var_Test = zeros(1,2000);  

 for i=3:1:2000        
     if AA(i)<=AA(i-1) && AA(i-1)<=AA(i-2)
         var_Test(i)=1;        
     else
         if AA(i)<=AA(i-1) && AA(i-1)>AA(i-2)
             var_Test(i)=2;
         else  % you forgot this else
             if AA(i)>AA(i-1) && AA(i-1)<=AA(i-2)        
                 var_Test(i)=3;
             else
                 if AA(i)>AA(i-1) && AA(i-1)>AA(i-2)        
                     var_Test(i)=4;          
                 end
             end
         end
     end
 end

 Vecteur_retour = var_Test;

Careful indentation would have helped here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜