Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
Dan Ibarra
Dan Ibarra el 12 de Mayo de 2021
Comentada: Dan Ibarra el 13 de Mayo de 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]

Respuesta aceptada

Walter Roberson
Walter Roberson el 12 de Mayo de 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,[]).';

Más respuestas (1)

Chunru
Chunru el 12 de Mayo de 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.

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by