Correct evaluation of a logical statement, incorrect result?

1 回表示 (過去 30 日間)
Geoff Luck
Geoff Luck 2019 年 3 月 5 日
コメント済み: Geoff Luck 2019 年 3 月 6 日
Hi,
I’m trying to create a 96 x 6 matrix, using a logical if statement to select the desired combination of values derived from performing one of two different operations on an existing 96 x 6 matrix. Like this:
if A <= 0.4
B = C ./ D;
else B = C .* D;
end
For each element in the matrix, if an element in A is less than or equal to 0.4, divide the equivalent element in C by D; if an element in A is greater than 0.4, multiply the equivalent element in C by D.
A is a 96 x 6 matrix of values that vary from 0 to 2.
B is the final 96 x 6 matrix I’m seeking.
C is a 96 x 6 matrix.
D is a scalar.
The logical statement produces the correct combination of 0s and 1s to index the locations on which to perform the desired operation, but the final matrix is composed entirely of elements produced by C .* D.
Can anyone offer any suggestions?
Thanks!

採用された回答

Dennis
Dennis 2019 年 3 月 5 日
It would be helpful to see your code, to find any errors. This should work fine:
A=rand(96,6);
D=5;
B=zeros(96,6);
C=3*ones(96,6);
B((A<=0.4))=C(A<=0.4)./D;
B((A>0.4))=C(A>0.4)*D;
  1 件のコメント
Geoff Luck
Geoff Luck 2019 年 3 月 6 日
Thanks so much, Dennis, works like a dream!

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2019 年 3 月 6 日
As Dennis suggested, you should use logical indexing. But as for why this behaves the way it does:
For each element in the matrix, if an element in A is less than or equal to 0.4, divide the equivalent element in C by D; if an element in A is greater than 0.4, multiply the equivalent element in C by D.
That's not what the code you wrote does. The if statement is not any sort of looping construct. When you specify a non-scalar condition the documentation says:
"if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
The expression in your call is A <= 0.4 and that will only be nonempty and contain only nonzero elements if A is not empty and all the elements of A are less than 0.4. The if keyword doesn't run its statements just for those elements of the expression that are nonzero.
  1 件のコメント
Geoff Luck
Geoff Luck 2019 年 3 月 6 日
Many thanks for the extra detail, Steven! I realise now that logical indexing is what I needed, and have since implemented it elsewhere I was struggling. Thanks again!

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by