how to check for a perfect square in a Matrix

i have a problem in which i have to return a value of true if any element of the matrix is a pefect square
for example
A = [ 2,4,7 ; 8,7,3 ]
b is true
otherwise
b is false

Answers (4)

A = [ 2,4,7 ; 8,7,3 ];
b = (mod(sqrt(A), 1) == 0)
A(b)

5 Comments

This will not work in this case
a = [20:30];
%%you can use this function
function b = isItSquared(a)
b = (mod(sqrt(a), 1) == 0)
cc = a(b);
if (~isempty(cc))
b = any(a==sqrt(cc));
if (b ==1)
b =1;
end
else
b=0;
end
end
Can you explain the function please
@Dawud Adam Rabiu if the number is a perfect square then the square root of it will be an integer, so that's what the mod checks for. If it's not a perfect square, there will be a fractional part so the mode of the number with 1 will be that fractional part, not 0. Only numbers with mod(sqrt(n))==0 will be perfect squares.
@Pallavi Chaudhary it seems to work fine if you use capital A:
A = [20:30];
b = (mod(sqrt(A), 1) == 0)
b = 1×11 logical array
0 0 0 0 0 1 0 0 0 0 0
A(b)
ans = 25
It correctly identifies 25 as the only perfect square in that vector (it's 5 squared). I'm not sure why you said it didn't work, but perhaps you used lower case "a" like you did. MATLAB is case sensitive so a is not the same as A.
The idea was to find if a matrix cotains two or more numbers for which num_x=(num_y)^2. or vice versa this code (mod(sqrt(A), 1) == 0) works perfectly for A = [ 2,4,7 ; 8,7,3 ] but it doesnt work for A=20:30; For that case the suggested solution below can be used, though it uses more memory.
for ii=1:length(a)
x(ii)=nnz(a==a(ii)^2);
if nnz(x)>0
b=true;
else
b=false;
end
end

Sign in to comment.

Use sqrt() and floor() functions to see which elements are perfect squares. Then use any(__, 'all') function to check if any element is a perfect square.
function b = isItSquared(a)
if a(1)^2 == a(end)
b = true;
else
b=false;
end
end
this solution has some drawnbacks... i couldnt find anysolution

2 Comments

Note this code is not in fact a solution. Not even close. It compares only the square of the first element, compared then for some reason to the final element in the matrix.
Had you wanteed to use a loop, that would be possible, but this attempt is not close to that.
yes iu got the solution.. i just didn't understand the preoblem well

Sign in to comment.

function b = isItSquared(a)
M = size(a,1);
N = size(a,2);
b = false ;
for p=1:M
for i=1:N
% to compare one element with other in the same colomn
for j=1:N
if (a(p,i))^2 == a(p,j)
b = true ;
break % if we get one we stop
end
end
end
end

Categories

Products

Asked:

on 8 Oct 2020

Edited:

on 31 Oct 2022

Community Treasure Hunt

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

Start Hunting!