2013-05-02 212 views
1

給定一個數組,我必須在數組中打印數字,該數組必須是正數並且可以被2整除,如果條件不成立,則打印「只查找」一次。Matlab-While循環

我已經運行我的代碼,但得到「沒有找到」消息的整個陣列的長度。我如何編碼它只能說一次?

這裏是我的代碼:

numbers = [9 3 7 3]; 
i = 1;  
while i <= length(numbers) 
    if numbers(i)>0 && mod(numbers(i),2) == 0 
     disp(numbers(i)) 
    else 
     disp('didint find') 
     i = i + 1; 
    end 
end 

回答

2
numbers = [9 3 7 3]; 
found = false; %This is a boolean flag used to see if we have found a number fitting the rules. If we find no number, found will be still false at the end of the loop 

for i = 1:length(numbers) %A for loop is far more suited to this problem than your original while 

    if numbers(i)>0 && mod(numbers(i),2) == 0 

     disp(numbers(i)) 
     found = true; 

    end 
end 
if ~found 
    disp('Didn''t find'); 
end 

但在Matlab你能真正做到這一點,沒有循環,實際上它是最好不要使用循環。嘗試下面的代碼:

ind = numbers > 0 & mod(numbers,2) == 0; 
if ~any(ind) 
    disp('Didn''t find'); 
else  
    disp(numbers(ind)'); 
end 
+0

我該如何做一個loob? – auriga123 2013-05-02 11:58:16

+0

@ auriga123看到我的編輯,但第二個版本更好,你應該嘗試和理解。 – Dan 2013-05-02 12:03:01

+0

謝謝隊友!真棒代碼... – auriga123 2013-05-02 12:10:14