开发者

Loop to create matrix

I am trying to make a loop which will create a matrix of appropriate size. I need the matrix to be constructed of a specified number of elements which are pulled from another matrix and added together.

Here is some psuedo code:

    '

        n=10
        for x=1:1:n

            Kglobal=zeros(nxn)


        Kglobal(1,1)=1
        Kglobal(x+1,x+1)=Klocalx(2,1)
        Kglobal(x+1,x+2)=Klocalx(2,2)+Klocalx+1(1,1)'
if Kglobal(x+1,x+2)=(n+1,n)
   Kglobal(n,n)=Klocaln(2,2)
    end
end

When finished resulting in something like:

'  
 Kglobal=[ 1 0 0 0 0 0 0 0 0 0 0;
        Klocal1(2,1) Klocal1(2,2)+Klocal2(1,1) 0 0 0 0 0 0 0 0 0;
        0 Klocal2(2,1) Klocal2(2,2)+Klocal3(1,1) 0 0 0 0 0 0 0 0;
        0 0 Klocal3(2,1) Klocal3(2,2)+Klocal4(1,1) 0 0 0 0 0 0 0;
        0 0 0 Klocal4(2,1) Klocal4(2,2)+Klocal5(1,1) 0 0 0 0 0 0;
        0 0 0 0 Klocal5(2,1) Klocal5(2,2)+Klocal6(1,1) 0 0 0 0 0;
        0 0 0 0 0 Klocal6(2,1) Klocal6(2,2)+Klocal7(1,1) 0 0 0 0;
        0 0 0 0 0 0 Klocal7(2,1) Klocal7(2,2)+Klocal8(1,1) 0 0 0;
        0 0 0 0 0 0 0 Klocal8(2,1) Klocal8(2,2)+Klocal9(1,1) 0 0;
        0 0 0 0 0 0 0 0 Klocal9(2,1) Klocal9(2,2)+Klocal10(1,1) 0;
        0 0 0 0 0 0 0 0 0 Klocal10(2,1) Klocal10(2,2)];
'
开发者_如何学运维

Thanks!! I appreciate any help and will be checking frequently so if there is something I can try to explain better please let me know!


To create a matrix like that is quite simple using the spdiags function. For example,

a=1:5;
b=6:10;
c=spdiags([a',b'],[-1,0],5,5);

creates a sparse matrix that looks like this

 6     0     0     0     0
 1     7     0     0     0
 0     2     8     0     0
 0     0     3     9     0
 0     0     0     4    10

except that memory is allocated only for the non-zero elements. This should answer your question as to how to create such a matrix.

However, the question is, how do you get the a's and b's, which in your case are the bunch of Klocal matrices. It is not very clear as to what you're doing in your code. I'm guessing that they can be done as some compact matrix/cell operations, but cannot comment further with what's given.

Anyway, assuming you already have the Klocal matrices, this should be sufficient to get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜