Efficiently assigning class property in a quadruple loop?

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

回答(1 个)

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

1 个评论

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

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

提问:

2021-9-18

编辑:

2021-9-18

Community Treasure Hunt

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

Start Hunting!

Translated by