how to make symmetric matrix with vector of its non repeated elements?

6 ビュー (過去 30 日間)
ahmad
ahmad 2023 年 3 月 1 日
編集済み: Jan 2023 年 3 月 1 日
suppose we have non repeated elements of a matrix in a vector . I need to make a symmetric matrix by using this vector in matlab.
for example if we have :
v= [ 1 4 5 6 9 0]
the answer must be the matrix:
1 4 5
4 6 9
5 9 0
  1 件のコメント
Luca Ferro
Luca Ferro 2023 年 3 月 1 日
could you better define the rules of the reshape?

サインインしてコメントする。

採用された回答

Jan
Jan 2023 年 3 月 1 日
編集済み: Jan 2023 年 3 月 1 日
v = [1 4 5 6 9 0];
d = numel(v);
n = (sqrt(8 * d + 1) - 1) / 2; % Number of rows and colums
A = zeros(n, n);
A(tril(true(n, n))) = v;
A(triu(true(n, n))) = v % [EDITED, faster than transposing the mask]
A = 3×3
1 4 6 4 5 9 5 9 0
Or with a loop (assumably faster for large arrays):
k = 0;
A = zeros(n, n);
for i2 = 1:n
k = k + 1; % Diagonal element
A(i2, i2) = v(k);
for i1 = i2 + 1:n % Below and above diagonal
k = k + 1;
A(i1, i2) = v(k);
A(i2, i1) = v(k);
end
end
A
A = 3×3
1 4 5 4 6 9 5 9 0
  1 件のコメント
Jan
Jan 2023 年 3 月 1 日
編集済み: Jan 2023 年 3 月 1 日
Some speed comparisons:
tic
for k = 1:1e3
n = (k * (k+1)) / 2;
A = ToSymMatrix_vec(1:n);
end
toc
Elapsed time is 1.327950 seconds.
tic
for k = 1:1e3
n = (k * (k+1)) / 2;
A = ToSymMatrix_loop(1:n);
end
toc
Elapsed time is 0.839996 seconds.
function A = ToSymMatrix_vec(v)
d = numel(v);
n = (sqrt(8 * d + 1) - 1) / 2; % Number of rows and colums
A = zeros(n, n);
A(tril(true(n, n))) = v;
A(triu(true(n, n))) = v;
end
function A = ToSymMatrix_loop(v)
d = numel(v);
n = (sqrt(8 * d + 1) - 1) / 2; % Number of rows and colums
k = 0;
A = zeros(n, n);
for i2 = 1:n
k = k + 1; % Diagonal element
A(i2, i2) = v(k);
for i1 = i2 + 1:n % Below and above diagonal
k = k + 1;
A(i1, i2) = v(k);
A(i2, i1) = v(k);
end
end
end

サインインしてコメントする。

その他の回答 (1 件)

Pratheek
Pratheek 2023 年 3 月 1 日
The first line of the code is to input for the size of the matrix that you want to generate.
% ask the user for the size of the matrix
n = input('Enter the size of the square matrix: ');
% get the input vector
v = [1 4 5 6 9 0]; % or prompt the user to enter the vector as well
% create the symmetric matrix
M = zeros(n);
k = 1;
for i = 1:n
for j = (i+1):n
M(i,j) = v(k);
M(j,i) = v(k);
M(i,i) = v(randi(length(v)));
k = k + 1;
end
end
% display the resulting matrix
disp(M);
  1 件のコメント
Jan
Jan 2023 年 3 月 1 日
Why do you set the diagonal elements randomly and repeatedly in each iteration of the inner loop?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by