2016-07-25 8 views
2

用なしの-1行列の最小とインデックスを変更: 私は交換されて私は何をしたい3x3x2MATLAB:私は直接の例で状況を示すよループ

c(:,:,1) = [-1 2 3; 
      -1 5 6; 
      7 8 9]; 
c(:,:,2) = [ 11 12 -1; 
      13 14 15; 
      16 17 18]; 

である行列を持っていますとc(:,:,2)の最小値はそれぞれ211です。 -1の行列要素は、これらの値に置き換えてください。そして、その結果は次のようになります。私が今までやった

result(:,:,1) = [2 2 3; 
       2 5 6; 
       7 8 9]; 
result(:,:,2) = [ 11 12 11; 
        13 14 15; 
        16 17 18]; 

は次のとおりです。私は、forループせずに最小値を置き換えたい

d = max(c(:))+1; 
c(c==-1) = d; 
e = reshape(c,9,2); 
f = min(d); 

。これには簡単な方法がありますか?ここで

答えて

1

はそれを行うための方法です:

d = reshape(c,[],size(c,3)); % collapse first two dimensions into one 
d(d==-1) = NaN; % replace -1 entries by NaN, so min won't use them 
m = min(d,[],1); % minimum along the collapsed dimension 
[ii, jj] = find(isnan(d)); % row and column indices of values to be replaced 
d(ii+(jj-1)*size(d,1)) = m(jj); % replace with corresponding minima using linear indexing 
result = reshape(d, size(c)); % reshape to obtain result 
関連する問題