- A+

Category：Languages

So I have these 4 same-sized matrices:

`k = [0.5; 1.0; 1.5; 2.0]; l = [2; 4; 6; 8]; m = [1.7; 3.0; 4.5; 6.0]; n = [2.5; 5.0; 7.5; 10.0]; `

And I want to put the elements from each matrix into the diagonal of zero matrix, so it would create something like this:

`f = 0.5 2.0 0 0 0 0 0 0 1.7 2.5 0 0 0 0 0 0 0 0 1.0 4.0 0 0 0 0 0 0 3.0 5.0 0 0 0 0 0 0 0 0 1.5 6.0 0 0 0 0 0 0 4.5 7.5 0 0 0 0 0 0 0 0 2.0 8.0 0 0 0 0 0 0 6.0 10.0 `

This is what I've come up with:

`f = zeros(8,8); k = [0.5; 1.0; 1.5; 2.0]; l = [2; 4; 6; 8]; m = [1.7; 3.0; 4.5; 6.0]; n = [2.5; 5.0; 7.5; 10.0]; for i = 1:2:8 %odd index number for j = 2:2:8 %even index number f(i,i) = k(1,i) f(i,j) = l(1,i) f(j,i) = m(1,i) f(j,j) = n(i,1) end; end; disp(f) `

But the result put the elements not into the diagonal of matrix `f=zero(8,8)`

, and I've always got the error of `Index exceeds matrix dimensions.`

Can I get some pointers on how to fix this code?

I think you intended to write this:

`for i = 2:2:8 f(i-1,i-1) = k(i/2) f(i-1,i) = l(i/2) f(i,i-1) = m(i/2) f(i,i) = n(i/2) end `

Though there must be simpler ways to accomplish the same thing. For example, check out the function `blkdiag`

!