How to compare the index values in the different matrices

5 次查看(过去 30 天)
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

采纳的回答

Adam Danz
Adam Danz 2021-11-9
编辑:Adam Danz 2021-11-9
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 个评论
Utku Ceylan
Utku Ceylan 2021-11-10
编辑:Utku Ceylan 2021-11-10
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 2021-11-11
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by