0

I'd like to create new vectors from columns of an existing matrix. My code looks like:

Matrix=[1 2 3;4 5 6;7 8 9]; A=Matrix(:,1); B=Matrix(:,2); C=Matrix(:,3); 

I see that this code is not really elegant especially if I have a big number of columns, that's why I'm looking for something like:

[A B C]=Matrix; 

But Matlab said the matrix can't be assigned to multiple values. Is there another way?

2 Answers 2

2

use mat2cell to split your original matrix up and deal to assign the splitted data to the result variables A,B and C:

m = mat2cell(Matrix,size(Matrix,1),ones(1,size(Matrix,2))) [A,B,C] = deal(m{:}) 

Unfortunately the intermediary variable is needed (however there is the FEX function dealcell that solves this if you like one-liners)

Sign up to request clarification or add additional context in comments.

1 Comment

mat2cell and sisters seem to be very useful to me. I'll get a deep look on them.
-1

Why would you want to do this? (Just curious) Matlab is designed to work off of a matrix. Hence the name Matrix Labratory... But alas it is still possible.

I'm sure there's a more elegant solution but I'll let you ponder that. This should get you going.

Matrix=[1 2 3;4 5 6;7 8 9]; for i=1:size(Matrix,2) %number of rows eval(sprintf('A%d = Matrix(:,i)', i)); end 

A1 =

 1 4 7 

A2 =

 2 5 8 

A3 =

 3 6 9 

4 Comments

The Matrix is given in a file generated by an external server. The file contains also a lot of different data. I want to extract the 'useful' vectors and rename them so other people can understand (from the vectors names) what I'm programming.
Ok, you might also want to look into using cell arrays as a possiblity too then.
in this case, I would allow this kind of separation of variables. Op himself says the original matrix is just a lot of data thrown together in one big file
I understand that now, just didn't have that information when the question was first posed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.