First number in foor loop

6 views (last 30 days)
Eliska Paulikova
Eliska Paulikova on 19 Apr 2023
Answered: Steven Lord on 19 Apr 2023
Hello, this is a part of my code, I have a image analysis, where the program reading frames (h), however is starts to read due to the image changing. This means, that the h is not always start with 1, but it can starts with 5 or higher number. That is the problem with the code, where I have the part h==1. So how to change the code, to have
if h= first number of h
I dont know how to get the first number of the loop and remember it, because the loop change it every time. please help
Or how to write values to avoid giving the initial value
for h=1:100
tabulka1=...
if h==1
htabulka = tabulka1;
else
htabulka = [htabulka; tabulka1];
end
end

Answers (2)

Vilém Frynta
Vilém Frynta on 19 Apr 2023
Edited: Vilém Frynta on 19 Apr 2023
Hello,
you already know the whole vector h. If you want it's first value, you can keep saving the h value into a vector, and then call it's first value.
[🇨🇿] Můžeš ukládat h postupně do vektoru, a pak si můžeš kdykoliv zavolat první hodnotu.
An example:
% Vector to save your "h" values
v = [];
for h = 5:100
v(h) = h; % save the current "h" value into a vector
v = v(v > 0); % ignore zero values
if h == v(1) % compare h to first value
...
end
end
v(1) % the first number of iteration.
ans = 5
Hope I helped.

Steven Lord
Steven Lord on 19 Apr 2023
Don't hard code the first number. Store it in a variable that you can use to define the loop and then to retrieve the starting value afterwards.
firstNumber = 5;
for k = firstNumber + (0:9) % 10 iterations starting at firstNumber
fprintf("Loop body with k = %d.\n", k)
end
Loop body with k = 5. Loop body with k = 6. Loop body with k = 7. Loop body with k = 8. Loop body with k = 9. Loop body with k = 10. Loop body with k = 11. Loop body with k = 12. Loop body with k = 13. Loop body with k = 14.
fprintf("First number in the loop was %d.\n", firstNumber)
First number in the loop was 5.
If you've written a function to do your processing, you could even specify firstNumber as one of the inputs to the function.

Categories

Find more on Programming in Help Center and File Exchange

Tags

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!