Rewriting code for faster performance ( can it be written in matrix operations)

1 view (last 30 days)
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 Comments
Steven Lord
Steven Lord on 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.

Sign in to comment.

Answers (1)

Hari
Hari on 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:
  1. 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.
  2. 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. ismemberfunction 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.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!