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

前端 未结 3 620
余生分开走
余生分开走 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:49

    You can use direct indexing, and some faffing about with repmat, to add the indexes for a single 50x50 diagonal to the offsets within the larger matrix of each 50x50 block:

    Here's an example for a smaller problem:

    A = NaN(10,10,5,3);
    inner = repmat(sub2ind([10 10], [1:10],[1:10]), 5*3, 10); % diagonals
    outer = repmat([10*10 * [0:5*3-1]]', 1, 10*10); % offsets to blocks
    diags = inner + outer;
    A(diags(:)) = 1;
    

提交回复
热议问题