Rearrange elements even and odd columns into one vector

60 views Asked by At

I have a vector A8 with two columns in it, here are two rows:

24.0192018449307    48.0192018449307
72.0576055347920    96.0576055347920

I want to create a new vector A9 such that I get one column:

24.0192018449307
48.0192018449307
72.0576055347920
96.0576055347920

I have tried to use the following loop:

for j=1:4
   if mod(j,2)~=0
        A9(j)=A8(j,1);
   else 
        A9(j)=A8(j,2);
    end
end

Obviously, this doesn't work because A8 has size 2x2, not 1x4.

But I can't figure it out.

I have tried using two loops:

for i=2;
  for j=1:4
      if mod(j,2)~=0
         A9(j)=A8(i,1);
      else
         A9(j)=A8(i,2);
      end
  end
end 

But this gives me A9 that has just the two elements of the second row repeated.

How can I rearrange this matrix?

1

There are 1 answers

0
Adriaan On BEST ANSWER
A =   [24.0192018449307  48.0192018449307;
       72.0576055347920  96.0576055347920];
B = A.';
B = B(:)

Using the fact that MATLAB is column-based, and thus you can transpose your matrix and then use the colon operator to get a single vector.

By the way, using variable names like A8 and A9 smells really bad. Like dynamic variable naming bad. You'll run into loads of trouble later on by giving your variables dynamic names, or unclear names like that.