How to fast process a calculation within a matrix without using a loop?

1 回表示 (過去 30 日間)
Leon
Leon 2019 年 3 月 29 日
編集済み: Leon 2019 年 3 月 29 日
I have a huge matrix A, and what i need to do is to go through each of the matrix element and do this below simple calculation:
[m n] = size(A);
for i=1:m
for j=1:n
B(i,j) = 10^-A(i,j);
end
end
The thing is that it is slow. Is there a way I can avoid the loop and make it faster?
Thank you!
  4 件のコメント
Rik
Rik 2019 年 3 月 29 日
編集済み: Rik 2019 年 3 月 29 日
Whenever the size of an array increases, Matlab has to create a copy in memory. This takes a lot of time if you repeat that very often. Your original code would cause the output to be extended m+n-1 times.
Pre-allocation would solve this issue by creating an array in advance of the correct size. If array processing is not possible, it is generally worth it to pre-allocate the output array.
Leon
Leon 2019 年 3 月 29 日
Got you!
Many thanks!

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

採用された回答

Rik
Rik 2019 年 3 月 29 日
Yes, use the power of array processing in Matlab:
B=10.^-A;
  2 件のコメント
Leon
Leon 2019 年 3 月 29 日
Many thanks!
Will that be a problem, if my data also contains NaNs?
Rik
Rik 2019 年 3 月 29 日
It will do the same as your loop for NaN values, so the B matrix will contain NaN everywhere where A has a NaN.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by