Consider the following example, for a user specified odd number of N = 5
one should see the following output:
A = [1 4 2 5 3];
For N = 7
: A = [1 5 2 6 3 7 4];
In more general form for an odd number N
:
A = [1 ceil(N/2 1) 2 ceil(N/2 2) ... N ceil(N/2)];
I went about the problem like this
A = zeros(1, N);
a1 = 1:ceil(N/2): a2 = ceil(N/2 1):N;
j = 1; k = 1;
for i = 1:N
if rem(i, 2) ~= 0
A(i) = a1(j);
j = j 1;
else
A(i) = a2(k);
k = k 1;
end
end
I feel that there are better ways of coding the problem, optimisation and simplicity-wise. I would appreciate it if you could guide me toward what I am seeking.
CodePudding user response:
A one linear solution:
A([1:2:N, 2:2:N]) = 1:N;
It can be regarded as the combination of these index operations:
A(1:2:N) = 1:(N 1)/2;
A(2:2:N) = (N 3)/2:N;