for loop for different set of values
106 views (last 30 days)
Show older comments
Hi, i want to run for loop with different set of values as for example
for i = 2:6,17:22
Y= 2*i;
End
Please do it ASAP
Accepted Answer
Tim
on 22 Jun 2015
Edited: Tim
on 22 Jun 2015
A more polite way to ask in the event of urgency would be something like:
"I really need help on this one, time is a factor!"
a =[2:6 17:22]
for i=1:length(a)
y=2*a(i)
end
Or if you want to do it without a loop use vector form, which is generally more efficient in MATLAB:
a =[2:6 17:22];
y=2.*a;
0 Comments
More Answers (2)
Azzi Abdelmalek
on 22 Jun 2015
Edited: Azzi Abdelmalek
on 22 Jun 2015
It's better to avoid the variable i, because it's used by Matlab with complex numbers.
for ii= [2:6,17:22]
Y= 2*ii;
end
0 Comments
Walter Roberson
on 22 Jun 2015
for i = [2:6,17:22]
Y = 2*i;
end
Note that you are overwriting Y completely each time, which is a common error in for loops. When you are looping over values that are not consecutive integers and you want to get one output value for each input value then use something like
ivals = [2:6,17:22];
for k = 1 : length(ivals);
i = ivals(k);
Y(k) = 2 * i;
end
2 Comments
Amir Mohammad Babaie Parsa
on 25 May 2022
Edited: Amir Mohammad Babaie Parsa
on 25 May 2022
Hi
It really helped me, Thanks a zillion.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!