Fastest way to insert array into another array

6 次查看(过去 30 天)
Hello,
A portion of the code I'm working on writes a logical array of 1's to a specific location in a larger sparse array. The example below is done in 2 dimensions, but I have the ndSparse class and will be implementing this in 3 and higher dimensions as well:
A = sparse(10000,10000);
xStart = 1;
xEnd = 200;
yStart = 400;
yEnd = 600;
A(yStart:yEnd,xStart:xEnd) = true; % Possible speed improvement?
This segment of code will be repeated multiple times to insert multiple smaller logical arrays of 1's into various locations of A. Does anyone know of a faster way to accomplish what's being done in the final line? So far I've tested these methods:
A(yStart:yEnd,xStart:xEnd) = true; %Fast
A(yStart:yEnd,xStart:xEnd) = 1; %Fast
A(yStart:yEnd,xStart:xEnd) = true(yEnd-yStart+1,xEnd-xStart+1); %Slow
A(yStart:yEnd,xStart:xEnd) = ones(yEnd-yStart+1,xEnd-xStart+1); %Slow
  1 个评论
dpb
dpb 2019-5-10
Probably not...the latter two examples have to create the alternate array each time and copy it; I'm guessing the optimizer can turn the constant copy straight to code for the contiguous area. As you get into higher dimensions you may find slowdowns again depending on the arrangements

请先登录,再进行评论。

回答(1 个)

Sulaymon Eshkabilov
Use of size() can improve to certain extent:
A(yStart:yEnd,xStart:xEnd) = true(size(yEnd-yStart+1,xEnd-xStart+1));
A(yStart:yEnd,xStart:xEnd) = ones(size(yEnd-yStart+1,xEnd-xStart+1));
  1 个评论
dpb
dpb 2019-5-11
That's not what's wanted at all, though...
yEnd-yStart+1,xEnd-xStart+1 --> 201,200
size(yEnd-yStart+1,xEnd-xStart+1) --> size(201,200) --> 1
because the first argument to size() is a single double() value and the second argument to size is the dimension of the first argument along which to take the size magnitude. By convention, referring to any ML array by unneeded trailing dimension, even up to the 200th simply returns "1"
If you timed the above construct in comparison to OP's to ascertain it was faster, it's because of the resultant array being 1x1, not 200x201.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by