Check if element in array are square of each other
Show older comments
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
Accepted Answer
More Answers (4)
madhan ravi
on 22 Mar 2019
nnz(V.^2==V.')>=1 % where V your vector, result 0 means false, 1 means true
5 Comments
madhan ravi
on 22 Mar 2019
For versions prior to 2016b:
nnz(bsxfun(@eq,V.^2,V.'))>=1
madhan ravi
on 22 Mar 2019
So your function file would be:
function y = isItSquared(x)
y = nnz(bsxfun(@eq,V.^2,V.'))>=1 ;
end
And for calling the function:
V=[7 5 49];
y = isItSquared(V)
am
on 22 Mar 2019
madhan ravi
on 22 Mar 2019
Edited: madhan ravi
on 22 Mar 2019
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
on 22 Mar 2019
Steven Lord
on 22 Mar 2019
2 votes
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.
Agam Sharma
on 8 Jun 2022
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
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!