# Efficiently assigning class property in a quadruple loop?

2 views (last 30 days)
Justin Ng on 18 Sep 2021
Edited: Matt J on 18 Sep 2021
Is there a better way to assign values to a very complicated object with multiple nested classes and properties? I have the following piece of code in a quadruple loop right now, but it is a serious bottleneck in my code. Is there a better way of handling something like this?
for ind_1 = 1:N1
for ind_2 = 1:N2
for ind_3 = 1:N3
for ind_4 = 1:N4
if any(myLogicalVector)
obj.prop(ind_1).interaction(ind_2,ind_3,ind_4).interaction_flag = someFixedValue1;
else
obj.prop(ind_1).interaction(ind_2,ind_3,ind_4).interaction_flag = someFixedValue2;
end
end
end
end
end

Matt J on 18 Sep 2021
Edited: Matt J on 18 Sep 2021
You've not told us the dependence of myLogicalVector and someFixedValue* on the loop variables, which is probably super-important to know here. At minimum, though, this could be reduced to a double loop.
for i = 1:N1
interaction=obj.prop(i).interaction;
for j=1:N2*N3*N4
if any(myLogicalVector)
interaction(j).interaction_flag = someFixedValue1;
else
interaction(j).interaction_flag = someFixedValue2;
end
end
obj.prop(i).interaction=interaction;
end
Matt J on 18 Sep 2021
The best way to achieve performance gains would probably be to redesign the data structure itself. For example, I speculate that you do not need to have an N2xN3xN4 array of "interaction" property values. Instead, have "interaction" be a scalar property which holds an N2 x N3 x N4 array of interaction flags. If you can do that, the above could be reduced to,
for i = 1:N1
obj.prop(i).interaction.interaction_flag(logicalIndex)=someFixedValue1;
obj.prop(i).interaction.interaction_flag(~logicalIndex)=someFixedValue2;
end