IF statements to compare Imaginary Numbers

조회 수: 2 (최근 30일)
Kayne
Kayne 2011년 8월 21일
Hi,
I have been trying to work out how to use a IF statement to see if two imarinary matrixs are the same, then display "results re correct' or soething like that. My code is below
EG,
clear
clc
%-------------------Setting Up the Variables-------------------------------
X = [1, -1]' ; % The Orignal Funcation
X1 = [0, -1 - 1i]' ; % The Recieved Function
% -------------------Potential transforms matries for W -------------------
W1 = 1/(sqrt(2))*[1,1;exp(0),-exp(0)] ; % Transform 1
W2 = 1/(sqrt(2))*[1,1;exp(1i*pi/4),-exp(1i*pi/4)] ; % Transform 2
W3 = 1/(sqrt(2))*[1,1;exp(1i*pi/2),-exp(1i*pi/2)] ; % Transform 3
W4 = 1/(sqrt(2))*[1,1;exp(3i*pi/4),-exp(3i*pi/4)]; % Transform 4
%-------------------Solving to find the Value for X1-----------------------
A = W1*X ; % solves for Transform 1 and the orignal funcation
B = W2*X ; % solves for Transform 2 and the orignal funcation
C = W3*X ; % solves for Transform 3 and the orignal funcation
D = W4*X ;% solves for Transform 4 and the orignal funcation
Now the if statements that I have been working on are as follows
if A==X1
disp ('Resutls are the same')
elseif B==X1
disp ('Resutls are the same')
elseif C==X1
disp ('Resutls are the same')
elseif D==X1
disp ('Resutls are the same')
end
Now I know that the answer is D but continue to get nothing for the result. I have read about this and it has something to do with floating point numbers and what Matlabs can display. I am a little lost as to how the code should look so that the answer D will display something saying it is the same.
Any help would be appriciated
Thanks Kayne

답변 (2개)

Paulo Silva
Paulo Silva 2011년 8월 21일
Do this
D==X1
ans=
1
0
It's really something about floating point, try doing this:
(D>=X1-eps & D<=X1+eps)
now replace all the comparisons on your code the same way and all should work.
Better explanation and ways to deal with the situation can be found here
  댓글 수: 2
Kayne
Kayne 2011년 8월 21일
Thanks for the reply Paulo,
Your solution worked and has helped me greatly. Now to get into the finner details and understand why it worked.
Thanks heaps for your time and help
Kind Regards,
Kayne
Paulo Silva
Paulo Silva 2011년 8월 21일
Do this: X1-D , it isn't zero but very close to it, very near eps.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2011년 8월 21일

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by