MATLAB: How to make a loop(for…end)

matlab loop for

I'm a new guy for matlab loop. Righi now I want to now some rools about loop(for…end). Such as how to make a loop to get all odd numbers from a matrix x=[1:100] or numbers like 1,5,9,13,17,21…? p.s.I know this x1=x(1:2:100) and x4=(1:4:100),but I want to know how to get it from a loop(for…end).

Best Answer

It would be good if you learned to pre-allocate your vectors so your code runs efficiently...
.
.
.
EDIT In response to question about generalization.
The general case can be written:
N = 100; % The largest number. Change to whatever...
a = 1; % The starting point. Change to 3,5... whatever
n = zeros(1,ceil((N-a)/2)); % Pre-allocate the array...
for ii = 1:length(n)
n(ii) = 2*(ii)+(a-2);
end