How to increment and/or decrement with different values in the same loop
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Aren Kurumlian
am 4 Mär. 2018
Kommentiert: Benjamin Kraus
am 4 Mär. 2018
This is the code I have but I was wondering if there is a more simple and efficient way to implement this. Basically, I am going from 15 to 1 but instead of decrementing with a single value i.e [15 14 13 12 ... 2 1] I want to reach the target by different incrementation such as in the screenshot below the code i.e [15 14 18 16 13 12 ... 4 1]
i = 1;
v = 15;
array(i) = 15;
while array(i) ~= 1
i = i + 1;
v = v - 1;
array(i) = v;
if array(i) == 1
break;
end
i = i + 1;
v = v + 4;
array(i) = v;
if array(i) == 1
break;
end
i = i + 1;
v = v - 2;
array(i) = v;
if array(i) == 1
break;
end
i = i + 1;
v = v - 3;
array(i) = v;
end
disp(array)
0 Kommentare
Akzeptierte Antwort
Benjamin Kraus
am 4 Mär. 2018
Bearbeitet: Benjamin Kraus
am 4 Mär. 2018
Here is a version that is certainly shorter, and produces the same result, but I doubt it is any more efficient. The benefit I see to this version is that you can change the pattern more easily, and you don't have quite the same amount of redundant checks for whether the current value is 1.
pattern = [-1 4 -2 -3];
i = 1;
v = 15;
while v ~= 1
array(i) = v;
v = v + pattern(mod(i-1,numel(pattern))+1);
i = i + 1;
end
array(i) = v;
disp(array)
3 Kommentare
Benjamin Kraus
am 4 Mär. 2018
My code was this:
mod(i-1,numel(pattern))+1
Your version is this:
mod(i-1,numel(pattern)+1)
The difference is adding 1 after calling mod vs. adding one to the input to mod.
Breaking down my version when i == 1:
i == 1
i-1 == 0
numel(pattern) == 4
mod(i-1,numel(pattern)) == mod(0,4) == 0
mod(i-1,numel(pattern))+1 == mod(0,4)+1 == 1
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!