Better solution than mod() while indexing

조회 수: 4 (최근 30일)
Luke Heyerdahl
Luke Heyerdahl 2017년 11월 3일
답변: Guillaume 2017년 11월 3일
In this cutout, order is incremented each time through a loop, most likely more times than there are indexes in colors. Is there a better way to grab values in indexes in colors that avoids the if statement entirely?
ndx = (mod(order, length(colors));
if ndx = 0
ndx = length(colors);
end
color = colors(ndx));

답변 (1개)

Guillaume
Guillaume 2017년 11월 3일
Put the last colour first:
colors = [colors(end), colors(2:end-1)];
Then, simply mod and add 1:
color = colors(mod(ndx, numel(colors)) + 1);
If the loop just contains the code shown and the increment, then the loop can easily be eliminated. We would need to know how ndx is incremented though.

카테고리

Help CenterFile Exchange에서 Desktop에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by