First number in foor loop

7 次查看(过去 30 天)
Eliska Paulikova
Eliska Paulikova 2023-4-19
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

回答(2 个)

Vilém Frynta
Vilém Frynta 2023-4-19
编辑:Vilém Frynta 2023-4-19
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 2023-4-19
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by