开发者

In MATLAB, how to create diagonal with integers and zeros everywhere else using nxn matrix

I have to create an n x n matrix with 199, 409, 619,....210n-11 down the diagonal and zeros everywhere else.

Here is my M file so far:

function A = MyDiagMatrix(n)
     A = zeros(n,n);
     for i =199:210:210n-11
          eye(i);
     end
end

what am I doing wrong? Any help wo开发者_高级运维uld be great!


First your function initializes the matrix, A, but does nothing with it after. You need to modify the entry of A for your function to return anything more than the zero matrix.

You could use MATLAB's function diag which creates a diagonal matrix from a vector. for example

d=1:n; %# create vector 1,2,...,n
A = diag(d) %# create diagonal matrix with entries A(i,i) = i with i=1,2,...,n;

modify the input vector d to suite your needs


If you want it as a function ...

function [ a ] = MyDiagonalMatrix( n )
a = diag(199:210:210*n-11);
end

p.s. The credit for this should really go to Azim.


Here is the function you need :

@( n ) diag(199:210:210*n-11)

And the e.g. of calling it:

MyDiagonalMatrix(3)

Actual test in MATLAB R2012a:

>> MyDiagonalMatrix = @( n ) diag(199:210:210*n-11)

MyDiagonalMatrix = 

    @(n)diag(199:210:210*n-11)

>> MyDiagonalMatrix(3)

ans =

   199     0     0
     0   409     0
     0     0   619

>> MyDiagonalMatrix(5)

ans =

         199           0           0           0           0
           0         409           0           0           0
           0           0         619           0           0
           0           0           0         829           0
           0           0           0           0        1039

They meets your requirement: "an n x n matrix with 199, 409, 619,....210n-11 down the diagonal and zeros everywhere else."

Hope that helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜