Rewriting code for faster performance ( can it be written in matrix operations)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi all, I have this pices of code which I'm running like milion of time and I wander if there is a way to write it to run faster, Maybe if some matrix operation.
The code
For the following reg_buffer it gives the later Q, it basikly does counting up to length(P_map) which equlas 4 in this case.
Additional info:
This is an example of three elements of reg_buffer, which go to 50 elements, one of reg_buffer features is that each element can not be hight then the one on its left. reg_buffer is acutely an address and Q is the unvisited addresses, [1 3 0] will inherently mean [13 1; 1 3 2; 1 3 3; 1 3 4].
r=find(reg_buffer, 1, 'last' );
Done = false;
while Done == false
for i=1:length(P_map)
reg_buffer(r)=reg_buffer(r)+1;
if reg_buffer(r)>length(P_map)
reg_buffer(r)=0;
r=r-1;
if r==0
Done = true;
break;
end
else
if ~any(ismember(Q,reg_buffer,'rows'))
Q=[Q;reg_buffer];
end
end
end
end
2 Kommentare
Steven Lord
am 23 Aug. 2022
Perhaps if you tell us the sizes of the data variables on which you plan to run this code and give an explanation in words not code of the purpose of the code it will be easier for us to offer suggestions for how to more efficiently achieve that purpose.
Antworten (1)
Hari
am 5 Sep. 2023
Hi Yasir,
As per my understanding, you want to rewrite your code to gain performance in time. You can consider the below optimizations:
- One potential optimization is to pre-allocate the “Q” matrix to avoid resizing it during each iteration of the loop. After your “while” loop, the “Q” matrix can be trimmed to remove any excess rows.
- From the line “any(ismember(Q,reg_buffer,'rows'))” in your code, I understand that you are trying to find, if any element of “Q” is equal to “reg_buffer”. But using “any” function with “ismember” can be inefficient for your purpose. “ismember” function finds all the elements which are similar in both the arrays, outputs a logical array. “any” function iterates over the logical array and finds if there is a true value in the array. Instead, you can define a custom function for this, which stops after locating one common element using a “for” loop. This can significantly reduce time for larger elements as in your case.
Refer to the below documentations to learn more about “preallocation” and “ismember” function in MATLAB.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!