Fastest way to insert array into another array

7 Ansichten (letzte 30 Tage)
Matthew Vitagliano
Matthew Vitagliano am 9 Mai 2019
Kommentiert: dpb am 11 Mai 2019
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 Kommentar
dpb
dpb am 10 Mai 2019
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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov am 10 Mai 2019
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 Kommentar
dpb
dpb am 11 Mai 2019
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by