Pair sums (how to avoid duplication?)

조회 수: 1 (최근 30일)
Shiyun Li
Shiyun Li 2020년 4월 23일
답변: Deepak Gupta 2020년 4월 23일
Hi I try to print pairs of number has the sum 12 in the input matrix, but what can I do to aviod duplication? for example if 3 9 is doesn't need to print 9 3. Also what can I do if I always want the small number at the front?
Here is my code
%print every set of number that sum to target value t
clear;clc;
%input an matrix
a=input('Enter a matrix:');
t=12;
%check the size of the matrix
[rows,cols]=size(a);
%loop through
for r=1:rows
for c=1:cols
for i=1:rows
for f=1:cols
if a(r,c)+a(i,f)==t
disp(a(r,c));
disp(a(i,f));
end
end
end
end
end
  댓글 수: 3
Shiyun Li
Shiyun Li 2020년 4월 23일
%print every set of number that sum to target value t
clear;clc;
%input an matrix
a=input('Enter a matrix:');
%check the size of the matrix
[rows,cols]=size(a);
%loop through
for r=1:rows
for c=1:cols
for i=1:rows
for f=1:cols
if a(r,c)+a(i,f)==12
fprintf('%d,%d\n',a(r,c), a(i,f));
end
end
end
end
end
%command window
Enter a matrix:[1 3 5 4 6 2 9 12 7 11 8 0]
1,11
3,9
5,7
4,8
6,6
9,3
12,0
7,5
11,1
8,4
0,12
Shiyun Li
Shiyun Li 2020년 4월 23일
Here is one of the example, sorry I can explain more clearly. What I want is the pairs of number only print once if 3, 9 is printed then 9,3 will not. And what can I do if I want the smaller number at the front when I print the pair? Thank you.

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

답변 (1개)

Deepak Gupta
Deepak Gupta 2020년 4월 23일
Seems like you have already found the numbers which add up to the required number.
Now Save these numbers in an array with 2 columns. Then swap the column entries if column 1 element is larger than 2nd.
for i = 1:size(A, 1)
if(A(i, 1)>A(i, 2))
temp = A(i, 2);
A(i, 2) = A(i,1);
A(i,1) = temp;
end
end
Now to remove the repititive rows
A=unique(A,'rows')

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by