Effacer les filtres
Effacer les filtres

How to compare the index values in the different matrices

8 vues (au cours des 30 derniers jours)
Utku Ceylan
Utku Ceylan le 9 Nov 2021
Commenté : Adam Danz le 11 Nov 2021
Hello,
I am trying to solve the problem 23 in Introduction to Matlab. The question asks to find the perfect squares as shown below. You can see that both 2 and 2^2 are in the same matrix.
Input a = [2 3 4]
Output b is true
I want to compare the input matrix with the root squared one but I do not know how to compare . Here is my code but it does not work. Is there any function for doing that?
a = [2 3 4]
b = sqrt(a)
if a == b
disp('b is true')
else
disp('b is false')
end

Réponse acceptée

Adam Danz
Adam Danz le 9 Nov 2021
Modifié(e) : Adam Danz le 9 Nov 2021
See isequal.
Demo:
a = [2 3 4]
a = 1×3
2 3 4
b = sqrt(a)
b = 1×3
1.4142 1.7321 2.0000
ismember(a,b)
ans = 1×3 logical array
1 0 0
To understand why your conditional statement does not work, consider this example below.
if [true false false]
disp('TRUE')
else
disp('FALSE')
end
FALSE
if [true true true]
disp('TRUE')
else
disp('FALSE')
end
TRUE
  6 commentaires
Utku Ceylan
Utku Ceylan le 10 Nov 2021
Modifié(e) : Utku Ceylan le 10 Nov 2021
Thanks a lot. I changed my code which can be seen below. However, I could not pass almost all the tests although I got the desired result. I still do not get what is wrong with my code.
a = [2 3 4]
b = sqrt(a)
if any(ismember(b,a)) == 1
disp('b is true')
else
disp('b is false')
end
Let me copy and paste the question without changing. The question is in the "Introduction to MATLAB" problem group. The question says that:
Adam Danz
Adam Danz le 11 Nov 2021
I don't know what tests are performed but the code you shared produces the correct results. However, there is no need for the "==1" in your any() comment.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by