Help using the toeplitz function
古いコメントを表示
Hi guys,
I am trying to get to grips with the toeplitz function to create a large diagonal matrix.
I want a 20 x 20 matrix with -2 going to down the main diagonal and then 1 in the upper dioagonal and 1 in the lower diagonal.
So far, I have managed to get my -2 and 1 in the main and upper diagional, but when I try to create the lower diagonal, I get an error saying "Too many inputs".
Here is the code:
n = 20
Mat = toeplitz([-2,zeros(1,n-1)],[-2,1,zeros(1,n-2))
How do I amend this to get my desired matrix?
Many thanks.
1 件のコメント
How do I amend this to get my desired matrix?"
full(gallery('tridiag',10,1,-2,1))
回答 (2 件)
"-2 going to down the main diagonal and then 1 in the upper dioagonal and 1 in the lower diagonal."
That's symmetric so only one argument is needed
n = 10; % used 10 instead of 20 to make the result easier to see
r = [-2,1,zeros(1,n-2)];
toeplitz(r)
20x20 is not large by any measure I would ever imagine. 20000x20000 might be large. :) Of course, large is a purely subjective adjective, so is defined by the eyes of the beholder. Ok, large for some.
It sounds like you want a tridiagonal matrix, with -2 on the main diagonal, and 1 on the immediate sub and super-diagonals.
Anyway, why are you trying to use toeplitz? Surely you could have used diag simply enough.
As an example, I'll create a 10x10 matrix here to not overburden the window.
n = 10;
Mat1 = -2*eye(n) + diag(ones(1,n-1),-1) + diag(ones(1,n-1),1)
Remember there are always many ways to solve a problem. So if you just needed a tridiagonal matrix, that would have worked. Alternatively, you could have don it all in one call to spdiags. Again, many ways to solve any one problem, all of which are often equally as good. Gosh, we could have done it as easily using tril and triu...
-3*eye(n) + tril(triu(ones(n),-1),1)
Again, many ways...
But I suppose, if your homework assignment specifically required you to use toeplitz... Could you do this using toeplitz? Of course, and in fact, toeplitz would be the logical solution, and even arguably the best.
First, the line you wrote has a missing closing bracket. But more importanty, what is the first column of your desired matrix?
[-2 1 0 0 0 0 0 0 0 0]'
You left out the 1 there in what you wrote. You did put it in as the first row, so I'm not sure why you skipped the 1 in the first column. Fixing that, we see:
Mat = toeplitz([-2,1,zeros(1,n-2)],[-2,1,zeros(1,n-2)])
So what is wrong with what you wrote? What exactly produced the message of "too many inputs"?
Anyway, always remember that if you get stuck trying to solve a problem one way, there may be alternatives. We could probably offer a zillion of them.
カテゴリ
ヘルプ センター および File Exchange で Operating on Diagonal Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!