필터 지우기
필터 지우기

How to use unique in a conditional statement nested in for loop?

조회 수: 1 (최근 30일)
Usman Saleem
Usman Saleem 2021년 1월 2일
댓글: Usman Saleem 2021년 1월 2일
I want to apply "unique" function on sol to get rid of repeated arrays.
n = 10000;
for a = 1:n
for b = 1:n
x = a^2-b;
y = sqrt(a^2+b^2);
if (mod(x,1)==0) && (mod(y,1)==0)
sol = [a,b]
end
end
end
So, for this code I tried
soln = unique(sol);
disp(soln)
But this approach displays only the last result due to loop. How can I fix it?

채택된 답변

Mischa Kim
Mischa Kim 2021년 1월 2일
Usman, you could do it this way. First compute all solutions in a matrix X and then compute unique values.
n = 1000;
for a = 1:n
for b = 1:n
x = a^2-b;
y = sqrt(a^2+b^2);
X(b + (a-1)*b,:) = [x y];
end
end
Y = unique(X,'rows');
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 1월 2일
Apply it afterwards.
Note: since your loops are over integers, x = a^2-b; is always an integer and does not need to be checked.
Usman Saleem
Usman Saleem 2021년 1월 2일
Yes, but these are dummy functions and will be change by the complex ones. Also, I will try to apply if statement afterwards.

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

추가 답변 (0개)

카테고리

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