Search code examples
arraysmatlabfor-loopcharindices

How do I reassign even and odd indices of a character array into a new smaller character array in Matlab?


In matlab I have a 32x1 character array A such that

A = {'F1' 'F2' 'F3' 'F4' 'F5' 'F6' ... 'F32'};
A = A';

Now I am trying to do the following with A. For every even index of A meaning

A{2}, A{4}, A{6}...

I want to assign those values to a 16x1 character array B and for the odd indices of A I want to assign those values to a different 16x1 array C.

I use the following code:

for i=1:32
 if mod(i,2)==0
   B{i} = A{i};
 else
   C{i} = A{i};
 end
end

and it works, but only partially because it assigns the right values at for e.g. B{2} and B{4} but the values in B{1} and B{3} are the same as in B{2} and B{4}.

Can anybody tell me how to reassign even and odd indices of a character array into a new smaller character array? My problem is that I am going from a 32x1 into a 16x1 and I'm not sure how to avoid the extra 16 entries.

Many thanks!


Solution

  • To get this question actual answered, use the idea of Luis Mendo in the comments. You can combine it with deal to save one line of code:

    [B, C] = deal(A(2:2:end), A(1:2:end))
    

    To make your loop work, you need a second running index jj:

    A = {'F1' 'F2' 'F3' 'F4' 'F5' 'F6'};
    
    for ii = 1:6
         jj = ceil(ii/2);
         if mod(ii,2)==0
            B{jj} = A{ii};
         else
            C{jj} = A{ii};
         end
    end