2012-12-11 133 views
1

我有一個矩陣,其中數字的每一行代表一個人值的矩陣.... =MATLAB:比較陣列以陣列

98 206 35 114 
60 206 28 52 
100 210 31 116 
69 217 26 35 
88 213 42 100 

(數字我這裏AREN真的是我的號碼) 我想比較person1 = [93 208 34 107]與的每一行。我發現哪個數組比另一個數組大,然後我將小數除以更大數。如果商數大於或等於0.85,則匹配並且該人員的姓名將打印到屏幕上。我應該使用一個循環和幾個if/else語句,如下所示?我相信有一個更好的方法來做到這一點。

for z = 1:5 
    if z == 1 
     a = max(person(z,:),person1); 
     b = min(person(z,:),person1); 
     percent_error = b/a; 
     if percent_error >= 0.85 
      title('Match,its Cameron!','Position',[50,20,9],'FontSize',12); 
     end 
    elseif z ==2 
     a = max(person(z,:),person1); 
     b = min(person(z,:),person1); 
     percent_error = b/a; 
     if percent_error >= 0.85 
      title('Match,its David!','Position',[50,20,9],'FontSize',12); 
     end 
    elseif z == 3 
     a = max(person(z,:),person1); 
     b = min(person(z,:),person1); 
     percent_error = b/a; 
     if percent_error >= 0.85 
      title('Match,its Mike!','Position',[50,20,9],'FontSize',12); 
     end 
     . 
     . 
     . 
     so on... 
    end 
end 

回答

4

對於初學者,您可以通過將所有名稱存儲在單元格中來刪除所有if語句。

allNames = {'Cameron'; 'David'; 'Mike'; 'Bill'; 'Joe'}; 

這裏是你如何那麼會得到他們抓住在一個循環:

person = [98 206 35 114; 
      60 206 28 52; 
     100 210 31 116; 
      69 217 26 35; 
      88 213 42 100]; 

person1 = [93 208 34 107]; 

allNames = {'Cameron'; 'David'; 'Mike'; 'Bill'; 'Joe'}; 

for z = 1:5 
    a = max(person(z,:),person1); 
    b = min(person(z,:),person1); 
    percent_error = b/a; 
    if percent_error >= 0.85 
     %title(['Match, its ', allNames{z} ,'!'],... 
     % 'Position',[50,20,9],'FontSize',12); 
     disp(['Match, its ', allNames{z} ,'!']) 
    end 
end 

運行代碼會顯示:

Match, its Cameron! 
Match, its David! 
Match, its Mike! 
Match, its Joe! 
+0

更好的是,有沒有一種方式,它只會表明它是匹配一個人,而不是提到其餘的。 – oldbutnew

+0

@oldbutnew你想要什麼?你想讓它只給你第一場比賽嗎? – user1884905

+0

是的,那就是我想要做的。當我得到真正的數字時,只有一個數組或者** person **中沒有數組應該匹配** person1 **數組。所以如果沒有匹配,我只想讓它說「找不到匹配!」一旦。我添加了一個else語句來表示「找不到匹配!」但它說每次沒有匹配。 – oldbutnew

0

根據你寫的東西,我的印象是你想要的比例實際上是

a=person(i,:) 
b=person1 % i=1..5 
a/b 

接近於一場比賽。 (由於A/B> = 0.85,如果A/B < = 1和B/A> = 0.85,如果B/A < = 1即0.85 < = A/B < = 1/0.85)

可以計算像這樣:

ratio = person/person1; 
idx = 1:5; 
idx_found = idx(ratio>=0.85 & ratio<1/0.85); 

for z=idx_found 
    disp(['Match, its ', allNames{z} ,'!']) 
end 
+0

不幸的是,如果某些值較小而其他值較大,則此代碼不起作用。例如'person1 = [80 120 80 120 80]'應該只與'person = [100 100 100 100 100]'的81.63%匹配,而此代碼與1.0的比率完美匹配。 – user1884905