Effacer les filtres
Effacer les filtres

How do I reshape a vector into a zero-diagonal matrix?

3 vues (au cours des 30 derniers jours)
Dan Ibarra
Dan Ibarra le 12 Mai 2021
Commenté : Dan Ibarra le 13 Mai 2021
I have these vectors:
x=[1;2;3;4;5;6;7;8;9;10;11;12]
y=[1;2;3;4;5;6]
How do I reshape these vectors into:
A =
[ 0 1 2 3
4 0 5 6
7 8 0 9
10 11 12 0]
B=
[0 1 2
3 0 4
5 6 0]

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Mai 2021
x = [1;2;3;4;5;6;7;8;9;10;11;12];
nx = numel(x);
n = ceil(sqrt(nx));
if nx ~= n*(n-1)
error('vector is wrong size to make square out of')
end
A = reshape([reshape([zeros(1, n-1);reshape(x, n, [])],1,[]), 0],n,[]).';

Plus de réponses (1)

Chunru
Chunru le 12 Mai 2021
Try this:
x=[1;2;3;4;5;6;7;8;9;10;11;12]
% y=[1;2;3;4;5;6]
m = 4; % matrix size
a = [zeros(m-1,1), reshape(x, m, m-1)' ]'; % 1st (m-1)*(m+1) elements
a = reshape([a(:); 0], m, m)' % add last 0 and reshape
B can be obtained in a similar way.

Catégories

En savoir plus sur Statistics and Machine Learning Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by