Pair sums (how to avoid duplication?)
1 次查看(过去 30 天)
显示 更早的评论
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
回答(1 个)
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')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!