MATLAB: Hi All, My question to all is that ………. I have to add the elements with in the matrix………

aa

2 1 2
1 1 1
1 1 1
i want to add a(1,2)and a(2,1) and then multiply it with a(1,1) and so on for each element to generate a new matrix……..
for a(2,2)….. we will have to do a(2,2) * ( a(1,2)+a(2,3)+a(3,2)+ a(2,1))
this a simple case and i have made the program for 3 by 3 matrix……. but how to generalize it for and n X n Matrix, where n is any number.
thanks for your guidance……….

Best Answer

  • Let A be an n-by-n matrix.
    B = [zeros(1,n+2);zeros(n,1),A,zeros(n,1);zero(1,n+2)]; % Create a border of all zeros
    B = A.*(B(1:n,2:n+1)+B(3:n+2,2:n+1)+B(2:n+1,1:n)+B(2:n+1,3:n+2)); %Corrected
    B will be the desired n-by-n matrix.