2013-05-01 33 views
2

我想澄清一下如何控制從MATLAB函數的變量返回,對於〔實施例讓我們考慮這個代碼如何控制MATLAB返回變量

function [x y z]=percentage(a) 
n=length(a); 
    maximum=0; 
    minimum=0; 
    subst=0; 
minus=0; 
plus=0; 
minus_perc=0; 
plus_perc=0; 
    for i=1:1:n 
     if a(i)>0 
      plus=plus+1; 
     else 
      minus=minus+1; 
     end 
end 
     minuc_perc=minus/n; 
     plus_perc=plus/n; 
       maximum=max(minus_perc,plus_perc); 
        minimum=min(minus_perc,plus_perc); 
        subst=maximum-minimum; 
        x=plus_perc; 
        y=minus_perc; 
        z=subst*100; 
        if plus_perc>minus_perc 
         disp('among the successful people,relevant propession was choosen by'); 
         disp(z) 
         disp('% people'); 
        else 
         disp('among the successful people,irrelevant propession was choosen by'); 
         disp(z); 
         disp('% people'); 
        end 

    end 

我想回到什麼是plus_procmin_procsubst ,但是當我運行下面的命令,結果得到這樣

[c d e]=percentage(a) 
among the successful people,relevant propession was choosen by 
    58.3333 

% people 

c = 

    0.5833 


d = 

    0 


e = 

    58.3333 

,所以我覺得什麼是錯的,陣列是這樣

a = 

    1 -1  1  1 -1  1 -1 -1  1  1  1 -1 

這樣的人再一次,我想回到plus_procminus_procsubst

+0

我發現我的錯誤,而不是minus_proc,有minuc_proc,對不起一個。如果你喜歡答案,我會upvote並接受 – 2013-05-01 14:09:55

回答

5

要返回MATLAB中的一個變量,你只分配到指定的回報參數之一。例如:返回數字五,我會用:

function [foo] = gimmeFive() 
    foo = 5; 
end 

你的代碼是不是給你正確的答案,因爲你有一個錯字:

minuc_perc=minus/n; 

應該

minus_perc=minus/n; 

通過利用find函數,可以極大地簡化函數,如下所示: 查找> 0的任何元素的元素,對它們進行計數。

plus = length(find(a > 0)); 
plus_perc = plus ./ length(a); 

或者,如果你想減少甚至多出: α> 0讓我們0和1的矢量,所以總結1的

plus = sum(a > 0); 
plus_perc = plus ./ length(a); 
+0

非常感謝@Alan – 2013-05-01 14:21:16