Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
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]

Risposta accettata

Walter Roberson
Walter Roberson il 12 Mag 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,[]).';

Più risposte (1)

Chunru
Chunru il 12 Mag 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.

Categorie

Scopri di più su Statistics and Machine Learning Toolbox in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by