Add a diagonal of zeros to a matrix in MATLAB

后端 未结 3 1327
温柔的废话
温柔的废话 2021-01-12 03:27

Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
          


        
3条回答
  •  粉色の甜心
    2021-01-12 04:18

    Generate a matrix with zeros at diagonal and ones at non-diagonal indices. Replace the non-diagonal elements with the transpose of A (since MATLAB is column major). Transpose again to get the correct order.

    B = double(~eye(N));  %Converting to double since we want to replace with double entries
    B(find(B)) = A.';     %Replacing the entries
    B = B.';              %Transposing again to get the matrix in the correct order
    

    Edit:

    As suggested by Wolfie for the same algorithm, you can get rid of conversion to double and the use of find with:

    B = 1-eye(N);
    B(logical(B)) = A.'; 
    B = B.';
    

提交回复
热议问题