How can I assign a value to the diagonals of a 4-D matrix using linear indexing in MATLAB?

前端 未结 3 621
余生分开走
余生分开走 2021-01-19 15:22

I have a 4-D matrix A of size NxNxPxQ. How can I easily change the diagonal values to 1 for each NxN 2-D submatrix in a vectorized way

3条回答
  •  遥遥无期
    2021-01-19 15:26

    Incorporating gnovice's suggestion, an easy way to index the elements is:

    [N,~,P,Q]=size(A);%# get dimensions of your matrix
    
    diagIndex=repmat(logical(eye(N)),[1 1 P Q]);%# get logical indices of the diagonals    
    A(diagIndex)=1;%# now index your matrix and set the diagonals to 1.
    

提交回复
热议问题