2017-04-08 104 views
0

我有一個N-M矩陣作爲GR輸入,它由以下數字組成:-3,0,2,4,7,10,12 而且我有返回一個向量。如果M = 1,那麼它應該只是返回輸入。從矩陣中刪除元素並計算平均值

如果M> 1它應該從矩陣中刪除最低的數字,然後計算其餘數字的平均值。 但是,如果行中的某個數字是-3,則它應該在輸出中返回值-3。

我對這個問題的看法:

是否可以做一個for循環?

for i=1:length(GR(:,1)) If length(GR(1,:))==1 GR=GR end If length(GR(1,:))>1 x=min(GR(i,:))=[] % for removing the lowest number in the row GR=sum(x)/length(x(i,:))

我只是沒有了如何檢測,如果該行中的任何數字的是-3,然後返回一個值,而不是計算平均值的任何想法時,我試圖刪除最低數字在矩陣中使用x = min(GR(i,:))matlab給了我這個錯誤按摩'刪除需要一個現有的變量'。

回答

0

你可以使用Nan的,nanmeananydim爭論這些功能:

% generate random matrix 
M = randi(3); 
N = randi(3); 
nums = [-3,0,2,4,7,10,12]; 
GR = reshape(randsample(nums,N*M,true),[N M]); 
% computation: 
% find if GR has only one column 
if size(GR,2) == 1 
    res = GR; 
else 
    % find indexes of rows with -3 in them 
    idxs3 = any(GR == -3,2); 
    % the (column) index of the min. value in each row 
    [~,minCol] = min(GR,[],2); 
    % convert [row,col] index pair into linear index 
    minInd = sub2ind(size(GR),1:size(GR,1),minCol'); 
    % set minimum value in each row to nan - to ignore it on averaging 
    GR(minInd) = nan; 
    % averaging each rows (except for the Nans) 
    res = nanmean(GR,2); 
    % set each row with (-3) in it to (-3) 
    res(idxs3) = -3; 
end 
disp(res) 
+0

你能解釋一下也許一些我用MATLAB的幫助突擊隊的代碼,但我不能肯定什麼idxs3,minCol和minInd確實 – Ryan

+0

我添加註釋解釋每一行。告訴我它是否還不夠清楚。 – user2999345

0

我把一個斷點功能。只要它檢測到-3值,就會從循環中斷開。其他功能也一樣。

請注意,它是一個i,j(M * N)矩陣。所以你可能需要改變你的循環。

for i=1:length(GR(:,1)) 

if GR(i,1)==-3 
GR=-3 
break 
end 

If length(GR(1,:))==1 

GR=GR 
break 
end 

If length(GR(1,:))>1 
x=min(GR(i,:))=[] % for removing the lowest number in the row 
GR=sum(x)/length(x(i,:)) 
end 

end 
+0

您首先需要清晰地定義您的決策層次結構。列出優先級列表,比編寫循環更容易。 – Joseph