필터 지우기
필터 지우기

How to compare the index values in the different matrices

조회 수: 8 (최근 30일)
Utku Ceylan
Utku Ceylan 2021년 11월 9일
댓글: Adam Danz 2021년 11월 11일
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