フィルターのクリア

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 Center および File ExchangeStatistics 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