how to do the matrix computation

1 回表示 (過去 30 日間)
Elysi Cochin
Elysi Cochin 2020 年 3 月 21 日
編集済み: Stephen23 2020 年 3 月 21 日
I have a cost matrix, c, with values as
c =[0,12,11,7,10,10,9,8,6,12;
12,0,8,5,9,12,14,16,17,22;
11,8,0,9,15,17,8,18,14,22;
7,5,9,0,7,9,11,12,12,17;
10,9,15,7,0,3,17,7,15,18;
10,12,17,9,3,0,18,6,15,15;
9,14,8,11,17,18,0,16,8,16;
8,16,18,12,7,6,16,0,11,11;
6,17,14,12,15,15,8,11,0,10;
12,22,22,17,15,15,16,11,10,0]
i wanted to do a computation
sij = c0i + c0j - cij
sij = sji;
and get store into a new matrix s as shown below

採用された回答

Stephen23
Stephen23 2020 年 3 月 21 日
編集済み: Stephen23 2020 年 3 月 21 日
>> M = c(1,2:end).' + c(2:end,1).' - c(2:end,2:end); % requires MATLAB >= R2016b
>> M = triu(M,1) + triu(M,1).'
M =
0 15 14 13 10 7 4 1 2
15 0 9 6 4 12 1 3 1
14 9 0 10 8 5 3 1 2
13 6 10 0 17 2 11 1 4
10 4 8 17 0 1 12 1 7
7 12 5 2 1 0 1 7 5
4 1 3 11 12 1 0 3 9
1 3 1 1 1 7 3 0 8
2 1 2 4 7 5 9 8 0
For earlier MATLAB versions you could use bsxfun or meshgrid:
>> [X,Y] = meshgrid(c(1,2:end),c(2:end,1));
>> M = X+Y-c(2:end,2:end);
>> M = triu(M,1) + triu(M,1).'
M =
0 15 14 13 10 7 4 1 2
15 0 9 6 4 12 1 3 1
14 9 0 10 8 5 3 1 2
13 6 10 0 17 2 11 1 4
10 4 8 17 0 1 12 1 7
7 12 5 2 1 0 1 7 5
4 1 3 11 12 1 0 3 9
1 3 1 1 1 7 3 0 8
2 1 2 4 7 5 9 8 0

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by