从矩阵中删除元素并计算平均值

时间:2017-04-08 12:23:18

标签: matlab loops matrix

我有一个N-by-M-Matrix作为输入,称为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给了我这个错误按摩'删除需要一个现有的变量。'

2 个答案:

答案 0 :(得分:0)

您可以在这些功能中使用Nannanmeananydim参数:

% 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) 

答案 1 :(得分: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
相关问题