%if true
for i iterations
Matrix = Matrix.*phase %Matrix has lot of zeros I want to skip multiplications with zero. Is it possible to do it in a single line without using if else or any loops
%end
Please dont use sparse, both matrix and phase are two-dimensional array

 採用された回答

Walter Roberson
Walter Roberson 2018 年 9 月 13 日

0 投票

Mask = Matrix ~= 0;
for i iterations
Matrix(mask) = Matrix(mask) * phase ;
end
This assumes that phase is a scalar nonzero value. It does not apply if phase is a vector or 2d array.
If phase is a 2d array then
phases = sparse(phase) ;
Matrix = sparse(Matrix) ;
for i iterations
Matrix = Matrix * phases;
end
Or better yet,
Matrix = sparse(Matrix) * (phase^iterations) ;
with no loop.

4 件のコメント

Walter Roberson
Walter Roberson 2018 年 9 月 14 日
In your revised specifications of 2D matrices and using .* then
mask = Matrix ~= 0; Matrix(mask) = Matrix(mask) .* (phase(mask).^iterations);
This does more multiplications than are strictly necessary if entries in phase can be 0. This code uses two statements; optimizing the multiplications for phase potentially being 0 would require three statements.
Walter Roberson
Walter Roberson 2018 年 9 月 14 日
There are also optimizations available to reduce the multiplications cost of phase.^iterations but at the potential cost of more memory. These are easiest to code if iterations is a constant. The requirement to use only a single line of code acts against the requirement to reduce multiplications. As I indicated before, if efficiency is the top priority then you should give up on trying to force everything into one line.
D_coder
D_coder 2018 年 9 月 14 日
編集済み: Walter Roberson 2018 年 9 月 14 日
actually this code is slow as compared to sparse. And sparse is slower as compared to the normal multiplication.Here is my detailed question. https://www.mathworks.com/matlabcentral/answers/418975-sparse-and-binary-mask
D_coder
D_coder 2018 年 9 月 14 日
Hey Walter my top priority is speed and saving multiplications.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2018 年 9 月 13 日

コメント済み:

2018 年 9 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by