MATLAB Answers

Improve use of structure in function

1 view (last 30 days)
Rub Ron
Rub Ron on 14 Jun 2020
Commented: Rub Ron on 2 Sep 2020
I have the following lines:
for x=1:800
for y=1:500
[mystruct(y).I] = ...
insideFunc( ...
mystruct(y).one(x),...
mystruct(y).two.pwr(x),...
mystruct(y).three.pwr(x),...
mystruct(y).four,...
mystruct(y).five,...
mystruct(y).six...
);
end
end
It seems most of the time of the simulation is spent on those line. My guess is that getting the values from the structure (to feed the function insideFunc) consumes a lot of time (once it gets inside InsideFunc, it executes relatively fast ). My question is: is there way to improve the code by changing the way to collect the input data for the function?

  3 Comments

Mohammad Sami
Mohammad Sami on 15 Jun 2020
Can you perhaps unnest your structure.
mytable = struct2table(mystruct);
Mohammad Sami
Mohammad Sami on 15 Jun 2020
Also do note that your code is overwriting the value for mystruct(y).I every time the value of x is incremented. Is this your intention ?
Rub Ron
Rub Ron on 2 Sep 2020
Thanks. Actually struct2table rise much more the computation time. mystruct(y).I is overwritten I changed it and did not notice an improvement in the timing.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 15 Jun 2020
It might possibly be more efficient to use
for x=1:800
for y=1:500
sy = mystruct(y);
[mystruct(y).I] = ...
insideFunc( ...
sy.one(x),...
sy.two.pwr(x),...
sy.three.pwr(x),...
sy.four,...
sy.five,...
sy.six...
);
end
end
In the special case where the vectors such as one() and two.pwr() are the same length for all entries, then there is potentially more acceleration available by using things like
my_ones = vertcat(mystruct.one);
After which
y_ones = my_ones(:,x);
for y = 1 : 500
.... y_ones(y)
end

  3 Comments

Rub Ron
Rub Ron on 15 Jun 2020
Thanks for your answer. I implemented your first suggestion only, and it did not improve the timing (actually the time increase a little more). I wanted to add the second suggestion but, I get an error get I try to concatenate :
vertcat(mystruct.two.pwr)
Expected one output from a curly brace or dot indexing
expression, but there were 500 results.
this concatenation works fine:
vertcat(mystruct.one)
Walter Roberson
Walter Roberson on 15 Jun 2020
What is size(mystruct.two) and size(mystruct.two.pwr) ?
Rub Ron
Rub Ron on 15 Jun 2020
mystruct.two is another structure, where pwr is one field. size of mystruct(1).two.pwr is 1x800 double

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!