have array entries filled depending on their indices?

1 回表示 (過去 30 日間)
Florian Rössing
Florian Rössing 2022 年 5 月 23 日
編集済み: Jan 2022 年 5 月 23 日
I want to fill an array
A=zeros(1000,1);
based on another array:
B=linspace(0,100,1000);
Now I want to fill every A(i) with the product of all B(k) with k=1:i-1, I do that alike this:
for i=1:length(A)
A(i)=prod(B(1:i-1));
end
For large sizes of A this becomes very time intensive. Would there be a way to do it faster? I couldnt find a way to use arrayfun for that.
And suggest I want to fill A(i), but do some more stuff inside the for loop?

回答 (1 件)

Jan
Jan 2022 年 5 月 23 日
編集済み: Jan 2022 年 5 月 23 日
The code is strange, because all elements of A are 0 except for the first one. B(1) is zero, so prod(B(1:n)) is zeros also. Maybe you mean:
n = 10000;
B = linspace(1,100,n); % Not starting at 0
tic
A = zeros(n, 1);
for i = 1:n
A(i) = prod(B(1:i-1));
end
toc
Elapsed time is 0.106487 seconds.
% Alternative: A naive loop avoiding repeated work:
tic
D = zeros(n, 1);
c = 1;
for i = 1:n
D(i) = c;
c = c * B(i);
end
toc
Elapsed time is 0.006453 seconds.
% Faster:
tic
C = [1, cumprod(B(1:n - 1))].';
toc
Elapsed time is 0.002222 seconds.
Even the loop is much faster than calculating the product from scratch in each iteration again. cumprod is much faster again.

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by