how to check for a perfect square in a Matrix
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (4)
KSSV
le 9 Oct 2020
A = [ 2,4,7 ; 8,7,3 ];
b = (mod(sqrt(A), 1) == 0)
A(b)
5 commentaires
Image Analyst
le 17 Sep 2022
@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)
A(b)
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.
Nick Austinos
le 22 Sep 2022
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
Ameer Hamza
le 8 Oct 2020
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.
0 commentaires
Ahmed Thawhid Sabit
le 15 Sep 2022
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 commentaires
John D'Errico
le 17 Sep 2022
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.
Ahmed Thawhid Sabit
le 18 Sep 2022
yes iu got the solution.. i just didn't understand the preoblem well
aimane nedjima
le 31 Oct 2022
Modifié(e) : aimane nedjima
le 31 Oct 2022
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
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!