Remove For Loops to Optimize Performance

1 回表示 (過去 30 日間)
Dinuk Amarasinghe
Dinuk Amarasinghe 2022 年 10 月 6 日
回答済み: Taru 2022 年 10 月 7 日
cvx_begin
y = 0;
n = 1000;
variables x;
minimize y;
parfor i = 1:n
y = -sum(log(1-x^2)) - sum(log(4 + rand(i)*x));
end
cvx_end
Need to remove for loops and write directly as vectors to speed up optimization algorithm.
  1 件のコメント
Torsten
Torsten 2022 年 10 月 6 日
rand(i) generates an (ixi) matrix of uniformly distributed random numbers on [0 1].
I doubt this is what you want.

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

回答 (1 件)

Taru
Taru 2022 年 10 月 7 日
Hi,
There seems to be a misunderstanding of the rand function as rand(i) gives a i*i square matrix of uniformly distributed random numbers between [0 1]. I understand that you might want it to generate n random numbers. So, you can just use rand(1,n) and vectorise it as:
y = -sum(log(1-x^2)) - sum(log(4 + rand(1,n)*x));
Without using any loop of sorts.

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by