How to decrease run time in swap operation ?
1 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I make the swap operation as shown below but it consumes time too much. Could you have any offer for swap operation in 2D array ?
while (firstPeriod <= totalPeriod && secondPeriod <= totalPeriod)
temp = myArray(firstPeriod, firstTelegramArray);
myArray(firstPeriod, firstTelegramArray) = myArray(secondPeriod, secondTelegramArray);
myArray(secondPeriod, secondTelegramArray) = temp;
firstPeriod = firstPeriod + rate;
secondPeriod = secondPeriod + rate;
end
Thanks in advance.
0 个评论
回答(2 个)
Walter Roberson
2019-11-23
编辑:Walter Roberson
2019-11-23
Before loop:
mysz = size(myArray);
In loop:
idx1 = sub2ind(mysz, firstPeriod, firstTelegramArray);
idx2 = sub2array(mysz, secondPeriod, secondTelegramArray);
myArray([idx1 idx2]) = myArray([idx2 idx1]);
This can be made more efficient at the expense of being less clear.
0 个评论
Guillaume
2019-11-23
What's the purpose of the while loop since you know beforehand when it ends and thus how many steps it will do?
Assuming that firstTelegramArray and secondTelegramArray are distinct (or that there's no overlap between the periods) your code is equivalent to:
%assuming that firstPeriod is initially StartfirstPeriod (not shown in your code)
%assuming that secondPeriod is initially StartsecondPeriod (not shown in your code)
firstPeriod = StartfirstPeriod:rate:totalPeriod;
secondPeriod = StartsecondPeriod:rate:totalPeriod;
%in case the two vectors have different length crop to the shorter one (same way the while loop behaves
minlength = min(numel(firstPeriod), numel(secondPeriod));
firstPeriod = firstPeriod(1:minlength);
secondPeriod = secondPeriod(1:minlength);
%now do all the swaps, this may be faster than using a temporary variable
indicesfirst = sub2ind(size(myArray), firstPeriod, repelem(firstTelegramArray, minlength));
indicessecond = sub2ind(size(myArray), secondPeriod, repelem(secondTelegramArray, minlength));
myarray([firstindices, secondindices]) = myarray([secondindices, firstindices]);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!