What is wrong with my while loop?

3 ビュー (過去 30 日間)
Jet Verheij
Jet Verheij 2018 年 2 月 15 日
コメント済み: Jet Verheij 2018 年 2 月 15 日
I have this big matrix, 592x528x903 single, called X. I want to see if the X(:,:,1) is not equal to any other in the matrix. I use this code:
b=2;
while b < 902
if X(:,:,1) ~= X(:,:,b)
b
end
b=b+1;
end
disp done
I get nothing on the screen, except done, so first I thought they all where equal. The problem is that if i use "equal to", i get the same response, nothing on the screen.
b=2;
while b < 902
if X(:,:,1) == X(:,:,b)
b
end
b=b+1;
end
disp done
Something is not working, they can't be both equal and not equal at the same time, or am I wrong?

採用された回答

Brendan Hamm
Brendan Hamm 2018 年 2 月 15 日
Your problem is that the result of
X(:,:,1) == X(:,:,b)
or
X(:,:,1) ~= X(:,:,b)
will return a logical matrix the same size as X(:,:,1) which apparently is never all true or all false and thus the if statement always evaluates to be false. The reson is this performs an element-wise comparison. If you want to check equality of the entire matrix, you should use the isequal function (isequaln if you want to ignore NaN in the matrices).
X = randi([0 1],2,2,902); % X with some equal pages.
b=2;
while b < 902
if isequal(X(:,:,1),X(:,:,b)) % or isequaln
b
end
b=b+1;
end
disp done
  1 件のコメント
Jet Verheij
Jet Verheij 2018 年 2 月 15 日
Thank you!

サインインしてコメントする。

その他の回答 (1 件)

KL
KL 2018 年 2 月 15 日
編集済み: KL 2018 年 2 月 15 日
Comparing matrices is easier if you use isequal command.
You should use it like,
if(isequal(X(:,:,1),X(:,:,b)))
What you're actually doing while using == or ~= is extracting a logical matrix as the result. Check this below example,
A = [1,2;3 4];
B = [1 0;3 4];
A==A
ans =
1 1
1 1
A==B
ans =
1 0
1 1
You see the problem?
Whereas, if you use isequal,
isequal(A,A)
ans =
1
isequal(A,B)
ans =
0
  1 件のコメント
Jet Verheij
Jet Verheij 2018 年 2 月 15 日
Thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by