1

I want to replace the diag between two matrices in matlab, for example: a =

 1     1     1
 1     1     1
 1     1     1

b =

 2     2     2
 2     2     2
 2     2     2

I want the function to do this: b =

 1     2     2
 2     1     2
 2     2     1

a =

 2     1     1
 1     2     1
 1     1     2

but instead of getting the final result, I am getting the all the inbetween results in the for loop// what i am doing wrong?

function [x] = may( a,b )
l1=length(diag(a));
l2=length(diag(b));
n=diag(a);
m=diag(b);

for i=1:l1
b(i,i)=n(i)

end

for j=1:l1
a(j,j)=m(j)

end
end
maymana
  • 45
  • 1
  • 5

2 Answers2

1

You ask for an output x, but it it never set in your functions. Furthermore, you don't use semicolons in lines b(i,i)=n(i) and a(j,j)=m(j). Furthermore, i is defined as i^2 = -1 in matlab, you are redefining it, try to avoid this.

function [aout, bout] = may( a,b )

l1=length(diag(a));
l2=length(diag(b));
n=diag(a);
m=diag(b);

for ii=1:l2
    b(ii,ii)=n(ii);

end

bout = b;

for jj=1:l1
    a(jj,jj)=m(jj);

end

aout = a;

end
Nick
  • 3,143
  • 20
  • 34
  • There was no problem in @user2463550's code with `i` and `j` being the imaginary unit. It's perfectly fine to use `i` and `j` for incrementation, and often clearer and more concise -enough with the paranoia. What is not good to do is use `i` and `j` as the imaginary variable (despite the default setting). Use `1i` (or `1j`). Matlab's `doc i` states this explicitly. – horchler Jun 07 '13 at 17:37
  • [further discussion about using `i` and `j` as variables](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Gunther Struyf Jun 08 '13 at 07:00
  • @Gunther Struyf: Seen it and I think most people new to Matlab will unfortunately get the wrong message from it. – horchler Jun 08 '13 at 22:02
0

If you assume the matrices are of same size and square, you can use logical indexing:

function [a, b] = may(a,b)
    diag_idx = logical(eye(size(a,1)));

    adiag = a(diag_idx);
    a(diag_idx) = b(diag_idx);
    b(diag_idx) = adiag;
end
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58