How can I assign a value to the diagonals of a 4-D matrix using linear indexing in MATLAB?
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? 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. You can actually do this very simply by directly computing the linear indices for every diagonal element, then setting them to 1: [N,N,P,Q] = size(A); diagIndex = cumsum([1:(N+1):N^2; N