Assigning values to the array of Enumeration Class seems to be very slow

27 views (last 30 days)
pingping zhang
pingping zhang on 20 Jan 2020
Commented: pingping zhang on 20 Jan 2020
Hi, I met this problem when parsing a gps log.
I made an Enumeration Class GpsState as follows.
classdef GpsState
Then I created an array of GpsState to record all the states of the log. The process was painfully slow.
Finally, I found out what the problem was caused by the assign of Enumeration Class array.
I simplified the code as follows, the process takes about 4.6s.
test_num = 1e5;
gps_state = repmat(GpsState.Lost,test_num,1);
for ii = 1:test_num
gps_state(ii) = GpsState.RTK_Fix;
Is there any problem with my usage mode of Enumeration Class?
Thanks for your reading.

Answers (1)

Steven Lord
Steven Lord on 20 Jan 2020
Why are you initializing all the elements in gps_state to GpsState.Lost in one call them immediately overwriting them with GpsState.RTK_Fix?
If you oversimplified your problem, and you wanted say) to only overwrite certain elements of gps_state, there's no need for a for loop here. Just overwrite them in one fell swoop, something like this untested code.
test_num = 1e5;
gps_state = repmat(GpsState.Lost, test_num, 1);
OneThousandRandomPoints = randperm(test_num, 1000);
gps_state(OneThousandRandomPoints) = GpsState.RTK_Fix; % scalar expansion
  1 Comment
pingping zhang
pingping zhang on 20 Jan 2020
Hey, there is some misunderstanding,that is my issue.
In actual fact, the original code contains a process of parsing and judging gps status.
I read gps status words from the log line by line, and assign gps_state values one by one.
It's something like this.
for ii = 1:test_num
switch gps_status_word(ii)
case "00"
gps_state(ii) = GpsState.Lost;
case "04"
gps_state(ii) = GpsState.RTK_Fix;
I found the process was particularly slow, and the root cause is the the assign of Enumeration Class array.
If I replace the Enumeration of GpsState by another tye like int8, for exmaple, 'gps_state(ii) = 0' , it will be much faster.
In order to describe the problem more simply, I use the code above. It shows us the elapsed time spent when assigning values to the array of Enumeration Class directly.
Now I can temporarily use int8 instead, but still want to make sure how to use Enumeration Class effectively.
Thanks for your advice.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!