prashant
prashant

Reputation: 1

splitting a Matrix into column vectors and storing it in an array

My question has two parts:

  1. Split a given matrix into its columns
  2. These columns should be stored into an array

eg,

A = [1 3 5 
     3 5 7
     4 5 7
     6 8 9]

Now, I know the solution to the first part:

the columns are obtained via tempCol = A(:,iter), where iter = 1:end

Regarding the second part of the problem, I would like to have (something like this, maybe a different indexing into arraySplit array), but one full column of A should be stored at a single index in splitArray:

arraySplit(1) = A(:,1)
arraySplit(2) = A(:,2)

and so on...

for the example matrix A,

arraySplit(1) should give me [ 1 3 4 6 ]'

arraySplit(2) should give me [ 3 5 5 8 ]'

I am getting the following error, when i try to assign the column vector to my array.

In an assignment  A(I) = B, the number of elements in B and I must be the same.

I am doing the allocation and access of arraySplit wrongly, please help me out ...

Upvotes: 0

Views: 13600

Answers (3)

Matt Phillips
Matt Phillips

Reputation: 9691

Really it sounds like A is alread what you want--I can't imagine a scenario where you gain anything by splitting them up. But if you do, then your best bet is likely a cell array, ie.

C = cell(1,3);
for i=1:3
   C{i} = A(:,i);
end

Edit: See @EitanT's comment below for a more elegant way to do this. Also accessing the vector uses the same syntax as setting it, e.g. v = C{2}; will put the second column of A into v.

Upvotes: 1

Malife
Malife

Reputation: 303

You could try something like the following:

A = [1 3 5; 
3 5 7;
4 5 7;
6 8 9]

arraySplit = zeros(4,1,3);

for i =1:3
    arraySplit(:,:,i) = A(:,i);
end

and then call arraySplit(:,:,1) to get the first vector, but that seems to be an unnecessary step, since you can readily do that by accessing the exact same values as A(:,1).

Upvotes: 0

guyrt
guyrt

Reputation: 927

In a Matlab array, each element must have the same type. In most cases, that is a float type. An your example A(:, 1) is a 4 by 1 array. If you assign it to, say, B(:, 2) then B(:, 1) must also be a 4 by 1 array.

One common error that may be biting you is that a 4 by 1 array and a 1 by 4 array are not the same thing. One is a column vector and one is a row vector. Try transposing A(:, 1) to get a 1 by 4 row array.

Upvotes: 0

Related Questions