How to compare the index values in the different matrices

7 views (last 30 days)
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

Accepted Answer

Adam Danz
Adam Danz on 9 Nov 2021
Edited: Adam Danz on 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 Comments
Utku Ceylan
Utku Ceylan on 10 Nov 2021
Edited: Utku Ceylan on 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 on 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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!