How to define both integer and decimal increment in one for loop?

Hi all,
I would like to define one for loop that goes from 0 to 1 with an increment of 0.1 and then goes from 1 to 30 by an increment of 2, i.e., combination of the following two loops. Is it possible? If so, how?
for n = 1:2:30
f(round((n-1)/2+1)) = ....
end
z = 0: 0.1: 1;
for n = 1: length(z)
f(n) = ..
end
Thanks in advance

 Réponse acceptée

Try this:
allValues = [0:0.1:1, 3:2:30];
numValues = length(allValues)
% Preallocate some results we want to store in the loop.
results = zeros(1, numValues);
% Now loop over all values.
for k = 1 : numValues
thisValue = allValues(k);
fprintf('Processing element #%d of %d, which is %f.\n', ...
k, numValues, thisValue);
% results(k) = YourFunction(thisValue);
end

Plus de réponses (1)

I'm not clear on what you're looking for. Do you want something like this:
span1 = 0:0.1:1;
span2 = 3:2:30;
span = [span1 span2];
for ii = span
% do something with ii...
end

7 commentaires

Thanks for your reply.
I want something like what you suggest however I don't know how to deal with the indices in the for loop. Any idea?
span1 = 0:0.1:1;
span2 = 3:2:30;
span = [span1 span2];
for ii = span
f(?) = something% do something with ii...
end
Do you want to do something like:
span1 = 0:0.1:1;
span2 = 3:2:30;
span = [span1 span2];
output = NaN(length(span),1);
for ii = 1:length(span)
output(ii) = some_function(span(ii));
end
Image Analyst
Image Analyst le 23 Juin 2021
Modifié(e) : Image Analyst le 23 Juin 2021
No. output(ii) will throw an error for fractional ii values.
What are you on about? ii will never be a fractional value.
Susan
Susan le 24 Juin 2021
Modifié(e) : Susan le 24 Juin 2021
Thank you so much, @Matthew for your help. Appreciate it!
@Matthew I suspect Image Analyst was replying to Susan's message not yours. The comment "do something with ii..." suggests to me (and I suspect to Image Analyst as well) that Susan wanted output(ii).
I was responding to Susan and just said No, then I went to MATLAB to develop code that works. Then I came back here to further explain why it wouldn't work and edited my comment but then I didn't notice miller's comment since it was posted while I was working on the code in MATLAB, and I mistakenly copied the loop from miller's comment instead of Susan's (not noticing that millers was a new comment). Sorry for the misunderstanding, that sometimes happens when people are posting at the same time. miller's code snippet #2 will also work for Susan.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by