필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Dan Ibarra
Dan Ibarra 2021년 5월 12일
댓글: Dan Ibarra 2021년 5월 13일
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]

채택된 답변

Walter Roberson
Walter Roberson 2021년 5월 12일
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,[]).';

추가 답변 (1개)

Chunru
Chunru 2021년 5월 12일
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.

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by