vectorize expression containing if statement

1 回表示 (過去 30 日間)
SA-W
SA-W 2023 年 7 月 13 日
コメント済み: the cyclist 2023 年 7 月 14 日
A = [-5 3 2;2 3 4; 3 5 6; -2 8 9];
%compute product of columns in a vectorized fashion
A(:,1).*A(:,2).*A(:,3);
%calculate the above product only for the rows where the entry in the first column is positive
%solution I do not like. A is not needed anymore after the calculation
A(~(A(:,1)>0),:) = [];
A(:,1).*A(:,2).*A(:,3)
ans = 2×1
24 90
Is there a way to get the above 2x1 result vector using one single line of code? I would also be happy with a 4x1 vector that contains NaN when the condition is not met. The issue is that my real A is quite large in size, so I want to be as efficient as possible and avoiding unnecessary copies or temporary variables related to the condition.

採用された回答

the cyclist
the cyclist 2023 年 7 月 13 日
編集済み: the cyclist 2023 年 7 月 13 日
Here is one way:
A = [-5 3 2;2 3 4; 3 5 6; -2 8 9];
prod(A(A(:,1)>0,:),2)
ans = 2×1
24 90
You could also have done the first operation as
prod(A,2)
ans = 4×1
-30 24 90 -144
  2 件のコメント
SA-W
SA-W 2023 年 7 月 13 日
"Product of columns" was actually just an example that I created, so prod() is not really what I am looking for.
In my real code, A has six columns that contain the six independent components of a 3x3 symmetric matrix. I wanna compute the trace of the inverse matrix (formulae known) , but only if the determinant of the matrix is greater than zero. Do you have an idea for that as well?
the cyclist
the cyclist 2023 年 7 月 14 日
This question is so different from what you oringally asked, that I'm wary of what is important.
Can't you just do
if det(M) > 0
<do the trace operation on M here>
end
?
If that isn't right, can I suggest you post a new question (because what you actually asked here was answered). You can upload your matrix using the paper clip icon in the toolbar, and then people can test code for speed on your actual data.

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

その他の回答 (0 件)

カテゴリ

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