本文介绍了给定矩阵的matlab代码,使用for循环通过添加行并找到最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这第一个矩阵表1包含5个名字和5个场景。我需要在这个矩阵上执行一些操作,我必须得到如表2所示的第二个矩阵。通过执行第一行,第二行,第三行等的相加,得到table2的对角线元素。比较2行并求和得到的剩余元素。假设以table1为矩阵,table2为B矩阵。 >
OPERATION1:对于对角元素
B(1,1)= 7 + 7 + 7 + 1 + 0 (2,2)= 6 + 0 + 0 + 0 + 0 = 6
B(3,3)= 0 + 6 + 0 + 4 = 22
B + 0 = 10 ......等等
操作2:对于其余元素
B(1,2)= MIN(A(1,1) ,A(2,1))+ MIN(A(1,2),A(2,2))+ MIN(A(1,4),A(2,4))+ MIN(A ),A(2,5));
B(1,3)= ..........
B(1,4)= ..........
B(1,5)= ..........
表1:
场景1场景2场景3场景4场景5
BASAVARAJ 7 7 7 1 0
MANOJ 6 0 0 0 0
NATESH 0 6 0 4 0
VIJAY 0 0 0 4 2
GOWDA 0 0 6 0 2
表2:
BASAVARAJ MANOJ NATESH VIJAY GOWDA
BASAVARAJ 22 6 7 1 6
MANOJ 6 6 0 0 0
NATESH 7 0 10 4 0
VIJAY 1 0 4 6 2
GOWDA 6 0 0 2 8
解决方案
代码
table1 = [
7 7 7 1 0;
6 0 0 0 0;
0 6 0 4 0;
0 0 0 4 2;
0 0 6 0 2];
table2 = NaN(size(table1));
for k1 = 1:size(table1,1)
for k2 = 1:size(table1,2)
rows_cat = [table1(k1,:);表1(K2,:)];
table2(k1,k2)= sum(min(rows_cat));
end
end
输出
table2 =
22 6 7 1 6
6 6 0 0 0
7 0 10 4 0
1 0 4 6 2
6 0 0 2 8
无循环版
%% //生成组合
vectors = {1:5,1 :5};
combs = combvec(vectors {:})。'; %% //'
t2 = reshape(combs',[],1); %//'
t4 = reshape(table1(t2,:)',5,2,[]); %/'
table2 = reshape(squeeze(sum(min(t4,[],2))),5,5)
组合代码片段摘自。
This first matrix table1 contains 5 names and 5 scenes.I need to perform some operations on this matrix and I have to obtain second matrix as shown in table2.
Diagonal elements of table2 should obtained by performing addition of 1st row,2nd row,3rd row..and so on.Remaining elements obtained by comparing 2 rows and summing them.Suppose take table1 as A matrix and table2 as B matrix.
OPERATION1:For diagonal elements
B(1,1)=7+7+7+1+0=22
B(2,2)=6+0+0+0+0=6
B(3,3)=0+6+0+4+0=10…….and so on
OPERATION2:For remaining elements
B(1,2)=MIN(A(1,1),A(2,1))+ MIN(A(1,2),A(2,2))+ MIN(A(1,4),A(2,4))+ MIN(A(1,5),A(2,5));
B(1,3)=..........
B(1,4)=..........
B(1,5)=..........
Table1:
Scene1 Scene2 Scene3 Scene4 Scene5
BASAVARAJ 7 7 7 1 0
MANOJ 6 0 0 0 0
NATESH 0 6 0 4 0
VIJAY 0 0 0 4 2
GOWDA 0 0 6 0 2
Table2:
BASAVARAJ MANOJ NATESH VIJAY GOWDA
BASAVARAJ 22 6 7 1 6
MANOJ 6 6 0 0 0
NATESH 7 0 10 4 0
VIJAY 1 0 4 6 2
GOWDA 6 0 0 2 8
解决方案
Code
table1 = [
7 7 7 1 0;
6 0 0 0 0;
0 6 0 4 0;
0 0 0 4 2;
0 0 6 0 2];
table2=NaN(size(table1));
for k1 = 1:size(table1,1)
for k2 = 1:size(table1,2)
rows_cat = [table1(k1,:) ; table1(k2,:)];
table2(k1,k2) = sum(min(rows_cat));
end
end
Output
table2 =
22 6 7 1 6
6 6 0 0 0
7 0 10 4 0
1 0 4 6 2
6 0 0 2 8
No-Loop version
%%// Generate combinations
vectors = {1:5,1:5};
combs = combvec(vectors{:}).'; %%//'
t2 = reshape(combs',[],1); %//'
t4 = reshape(table1(t2,:)',5,2,[]); %//'
table2 = reshape(squeeze(sum(min(t4,[],2))),5,5)
The combinations code snippet was taken from here.
这篇关于给定矩阵的matlab代码,使用for循环通过添加行并找到最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 06:12