如何在MATLAB中生成指定特征值的随机矩阵?是否有简便方法生成自定义特征值的随机矩阵?
Hey there! Let's break down your two MATLAB questions clearly—they're related but have key differences in how you approach them.
The go-to method here relies on similarity transformations: if two matrices are similar, they share the same eigenvalues. Here's the step-by-step approach:
- Create a diagonal matrix
Dwhere the diagonal entries are your desired eigenvalues. - Generate a random invertible matrix
P(orthogonal matrices work great here because their inverse is just their transpose, which is faster and numerically stable). - Compute your target matrix as
A = P * D * P'(orP * D * inv(P)if you're not using orthogonal matrices).
Example code
Suppose you want a 3x3 matrix with eigenvalues [2, -1, 0.5]:
% Define your desired eigenvalues eig_vals = [2, -1, 0.5]; n = length(eig_vals); % Generate a random orthogonal matrix (guaranteed invertible) P = orth(randn(n)); % Diagonal matrix of eigenvalues D = diag(eig_vals); % Compute the random matrix with specified eigenvalues A = P * D * P'; % Optional: Verify the result disp("Computed eigenvalues:"); disp(sort(eig(A))); % Should match sorted eig_vals (within floating point error)
If you don't need an orthogonal matrix, you can use a random Gaussian matrix—just make sure it's invertible (check the determinant to avoid singular matrices):
P = randn(n); % Re-generate if P is nearly singular while abs(det(P)) < 1e-10 P = randn(n); end A = P * D * inv(P);
If you want all eigenvalues to be the same (say, k), the above similarity trick with a diagonal matrix will just give you k*eye(n) (a diagonal matrix), which isn't very "random." To get a non-diagonal random matrix with identical eigenvalues, you need to use nilpotent matrices or Jordan canonical forms:
Method 1: Add a random nilpotent matrix to a diagonal matrix
A nilpotent matrix N has the property that N^n = 0 (for an n×n matrix). Adding this to k*eye(n) gives a matrix where all eigenvalues are k (since the characteristic polynomial becomes (x - k)^n).
Example code
For a 3x3 matrix with all eigenvalues equal to 5:
k = 5; n = 3; % Generate a random strictly upper triangular nilpotent matrix N = triu(randn(n), 1); % Create the target matrix A = k*eye(n) + N; % Verify disp("Eigenvalues of A:"); disp(eig(A)); % All should be ~5 (within floating point error)
Method 2: Similarity transformation on a Jordan block
If you want a more general random matrix (not just upper triangular), you can use a Jordan block (a matrix with k on the diagonal and 1s on the superdiagonal) and apply a similarity transformation:
k = 5; n = 3; % Create a Jordan block with all eigenvalues k J = k*eye(n) + diag(ones(n-1, 1), 1); % Use a random orthogonal matrix for similarity transformation P = orth(randn(n)); A = P * J * P'; % Verify disp("Eigenvalues of A:"); disp(eig(A)); % All ~5
This method gives you a fully random-looking matrix where every eigenvalue is your specified value.
内容的提问来源于stack exchange,提问作者N_A

