Info

此问题已关闭。 请重新打开它进行编辑或回答。

How to optimize this loop

5 次查看(过去 30 天)
Israel Campiotti
Israel Campiotti 2017-8-16
关闭: MATLAB Answer Bot 2021-8-20
I want to do a loop like this
for i = 1:n
A(i,B(i,1)) = 1;
end
but my matrix has size one million. Is there a way to do it faster?

回答(2 个)

Michelangelo Ricciulli
I think that this should save some time, since it avoids the for-loop:
i = 1:n;
A(i,B(i,1)) = 1;
  1 个评论
Image Analyst
Image Analyst 2017-8-16
In my testing that brought it from 0.01 seconds to 24 minutes.

Image Analyst
Image Analyst 2017-8-16
On my computer, it takes only 9 milliseconds for a million elements:
rows = 1000000;
columns = 5;
A = rand(rows, columns);
B = randi(columns, rows, 1);
tic
for k = 1 : rows
A(k, B(k)) = 1;
end
toc
Why do you need it faster?

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by