Efficiently assigning class property in a quadruple loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
Matt J
2021년 9월 18일
편집: Matt J
2021년 9월 18일
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
Matt J
2021년 9월 18일
편집: Matt J
2021년 9월 18일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!