What is another similar logic that is faster than

2019-07-20 19:11发布

问题:

Continue my research,

I need another similar logic with ismember that has execution time faster. this part of my code and the matrix.

StartPost =

    14    50    30     1    72    44    76    68    63    80    25    41;
    14    50    30     1    61    72    42    46    67    77    81    27;
    35    23     8    54    19    70    48    75    66    79     2    84;
    35    23     8    54    82    72    78    68    19     2    48    66;
    69    24    36    52    63    47     5    18    11    82     1    15;
    69    24    36    52    48    18     1    12    80    63     6    84;
    73    38    50     7     1    33    24    68    29    20    62    84;
    73    38    50     7    26    61    65    32    22    18     2    69]

for h=2:2:8,
    ...
       done=all(ismember(StartPost(h,1:4),StartPost(h-1,1:4)));
    ...
end

I checked that code by using Profile viewer. I got that in this part that made my code took time execution slowly.

Anyone has experience about this logic, please share. thanks

回答1:

MATLAB has several undocumented built-in functions which can help you achieve the same results as other functions, only faster.

In your case, you can use ismembc:

done = all(ismembc(StartPost(h, 1:4), sort(StartPost(h-1, 1:4)))));

Note that ismembc(A, B) requires matrix B to be sorted and not to contain any NaNs values.

Here's the execution time difference for your example:

tic
for h = 2:2:8
   done = all(ismember(StartPost(h, 1:4), StartPost(h-1, 1:4)));
end
toc

Elapsed time is 0.029888 seconds.


tic
for h = 2:2:8
   done = all(ismembc(StartPost(h, 1:4), sort(StartPost(h-1, 1:4))));
end
toc

Elapsed time is 0.006820 seconds.

This is about ~50 times faster.



标签: matlab random