MATLAB Answers

Matlab如何将cell中的矩阵进行合并?

조회 수: 17(최근 30일)
苏毅毅 苏
苏毅毅 苏 2021년 9월 18일
편집: Jan 2021년 9월 18일
Rule3={[3;2] [3;5] [4;2] [4;5] [5;2]};
请问如何判断Rule3中的矩阵第一行第一列是否相同,若是相同则要将两个矩阵合并,比如[3;2]∪[3;5]=[2;3;5],[4;2]∪[4;5]=[2;4;5],[5;2]没有于第一行第一列相同的数字5,所以直接保留。
最终,Rule3变成{[2;3;5][2;4;5][5;2]}。希望给出一个相对通用的答案,以为每次循环后,Rule3都会改变。
如有知道,还请不吝赐教,感谢!!!
  댓글 수: 1
Jan
Jan 2021년 9월 18일
An automatic translation:
Rule3={[3;2] [3;5] [4;2] [4;5] [5;2]};
How to judge whether the first row and the first column of the matrix in Rule3 are the same. If they are the same, merge the two matrices, such as [3;2]∪[3;5]=[2;3;5],[4; 2]∪[4;5]=[2;4;5], [5;2] does not have the same number 5 in the first row and first column, so keep it directly.In the end, Rule3 becomes {[2;3;5][2;4;5][5;2]}. I hope to give a relatively general answer, thinking that Rule3 will change after each loop.If you know, please feel free to enlighten me, thank you! !

댓글을 달려면 로그인하십시오.

답변(1개)

Jan
Jan 2021년 9월 18일
편집: Jan 2021년 9월 18일
R = {[3;2], [3;5], [4;2], [4;5], [5;2]};
nR = numel(R);
f = true(1, nR);
for iR = 1:nR
if f(iR) % If element was not disabled before
a = R{iR}(1); % 1st element
for jR = iR + 1:nR % Loop over following elements
if f(jR) % If element was not disabled before
if a == R{jR}(1) % Compare 1st element
R{iR} = [R{iR}; R{jR}(2)]; % Append contents
f(jR) = false; % Disable elemen for further tests
end
end
end
end
end
R = R(f); % Crop disabled elements
celldisp(R)
R{1} = 3 2 5 R{2} = 4 2 5 R{3} = 5 2

태그

Community Treasure Hunt

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

Start Hunting!