How to copy anti diagonal elements to another matrix?

Hello, I need to copy both diagonals from one matrix to another. For example:
If (i==j or i==n+1-j) : MatA(i,j)=MatB(i,j);
else: MatA(i,j)=MatB(i,j)+1;
Thanks

 Accepted Answer

Here is a simple solution using linear indexing. It assumes that both matrices are square and the same size.
>> A = randi(8,5)
A =
8 3 3 5 6
6 3 7 4 5
4 7 5 4 2
4 8 7 7 1
6 6 6 3 1
>> N = numel(A);
>> R = size(A,1);
>> V = [1:R+1:N,R:R-1:N];
>> B = A+1;
>> B(V) = A(V)
B =
8 4 4 6 6
7 3 8 4 6
5 8 5 5 3
5 8 8 7 2
6 7 7 4 1

More Answers (2)

KSSV
KSSV on 3 Nov 2017
Edited: KSSV on 3 Nov 2017
If A is your matrix. To get anti diagonal elements use:
diag(fliplr(A))
To get diagonal elements use:
diag(A)

1 Comment

And how do I copy the anti diagonal elements to a new matrix in the same places as the original one?

Sign in to comment.

A = randi(127,7)
B = randi(127,7)
s = size(A);
lo = eye(s) + flip(eye(s),2) > 0;
B(lo) = A(lo);

Categories

Asked:

on 3 Nov 2017

Edited:

on 3 Nov 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!