Check if element in array are square of each other

조회 수: 5 (최근 30일)
am
am 2019년 3월 22일
답변: Agam Sharma 2022년 6월 8일
Hello,
I have a problem where I have to find possible squares in an array. For example [7 5 49] or [49 5 7] is true since 7 squared is 49, but [11 13 25] should return false.
Is there a way to do it better than a nested loop?
Thank you!
function y = isItSquared(x)
y = false;
for i = 1:length(x)
for j = i+1:length(x)
if x(i)^2 == x(j) || x(i) == x(j)^2
y = true
break
end
end
end

채택된 답변

Mark Sherstan
Mark Sherstan 2019년 3월 22일
You can get rid of one of the for loops:
function y = isItSquared(x)
y = false;
xSquare = x.^2;
for ii = 1:length(x)
if (sum(x(ii) == xSquare) ~= 0)
y = true;
return
end
end
  댓글 수: 4
am
am 2019년 3월 22일
So if xSquare has no index, it means that the whole array is checked?
sum(x(ii) == xSquare) ~= 0
Mark Sherstan
Mark Sherstan 2019년 3월 22일
Correct, it is a boolean check returning an array of 1's or 0's.

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

추가 답변 (4개)

madhan ravi
madhan ravi 2019년 3월 22일
nnz(V.^2==V.')>=1 % where V your vector, result 0 means false, 1 means true
  댓글 수: 5
madhan ravi
madhan ravi 2019년 3월 22일
편집: madhan ravi 2019년 3월 22일
@eq means equal ,see https://in.mathworks.com/help/matlab/ref/bsxfun.html for further explanation.
https://in.mathworks.com/help/matlab/ref/nnz.html - nnz() gives you the total number of non-zero elements.
>= means if you have one or more then set it to true.
So what happens is each element of the vector is compared with the square of each element , so if atleast a single match is found then the answer returned is 1 meaning true.
am
am 2019년 3월 22일
I think it was a fantastic answer as well, thank you!

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


Steven Lord
Steven Lord 2019년 3월 22일
I would probably do this using some subset of the ismember, any, sum, all, and/or isequal functions. Read through the help text and see if you can think of a way to use some of those functions to accomplish that task.

KSSV
KSSV 2019년 3월 22일
a = [7 5 49] ;
b = [49 5 7] ;
idx = a.^2==b
In idx if 1 , true, if zero false.
  댓글 수: 1
am
am 2019년 3월 22일
Hello,
There is only one array being fed to the function.

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


Agam Sharma
Agam Sharma 2022년 6월 8일
function b = isItSquared(a)
b=false;
c=a.^2; %creating another array containing respective squares in 'a'
for i=1:length(c)
if(ismember(c(i),a)) %check if square is present in a itself
b=true;
end
end
end

카테고리

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