使用
A = magic(4);A(3,3)=nan; threshold=1; for ii = 1:size(A,1) % loop over rows if sum(isnan(A(ii,:)))>=threshold % get the nans, sum the occurances A(ii,:)=nan(1,size(A,2)); % fill the row with column width amount of nans end end
结果是
A = 16 2 3 13 5 11 10 8 NaN NaN NaN NaN 4 14 15 1
或者,正如@Obchardon在评论中提到的那样,你可以进行矢量化:
A(sum(isnan(A),2)>=threshold,:) = NaN A = 16 2 3 13 5 11 10 8 NaN NaN NaN NaN 4 14 15 1
作为旁注,您可以轻松地将其更改为列,只需为其他维度执行所有索引:
A(:,sum(isnan(A),1)>=threshold) = NaN;