How to extract columns of a matrix into seperate vectors?
1,952 views (last 30 days)
Show older comments
Hallo,
Let's assume a matrix (100x3). I want to extract out each of the columns, and store them in 3 separate vectors.
The code for the loop is clear, but what's the right code for storing each column?
----------------------------
for i = 1 : 3
vector = matrix(:, i);
end
----------------------------
I guess it's probably simple, but I am still a beginner and couldn't find much useful information in the documentation so far.
Thank you. Dominik
1 Comment
Oleg Komarov
on 7 Sep 2012
Edited: Oleg Komarov
on 7 Sep 2012
Why do you want to do that? And, don't do that. Storing your data has to be kept separate from the design you have in mind.
Answers (3)
Image Analyst
on 7 Sep 2012
Try this:
column1 = your2DMatrix(:, 1);
column2 = your2DMatrix(:, 2);
column3 = your2DMatrix(:, 3);
Unlike the others, I don't find any problem with doing this if referencing these 3 column vectors individually by name will make your code easier to understand and follow. It will certainly make your subsequent code more compact. I wouldn't do it if you had dozens and dozens of columns, but for only 3 I don't see a problem.
6 Comments
Stephen23
on 21 Nov 2017
Edited: Stephen23
on 21 Nov 2017
@Doina Gumeniuc: if you "went through this conversation" then you must have read the comments where very experienced MATLAB users and TMW staff recommend not doing this for a larger number of vectors.
Read this to know why they all agreed that this is a bad idea:
"so taking it one by one is a bit painful."
Yes, it is. And it is almost invariably a slow, buggy, complex way to write code, no matter how many beginners want to do this. What do you hope to achieve with 50 vectors in your workspace? How do you imagine passing 50 variables to SIN, or any other function? How would you search for those variables in the editor?
Doina Gumeniuc
on 25 Nov 2017
Hi Stephen, thank you for your reply, my bad for not noticing the information you mentioned. It is nice to have the possibility to ask for advice the more experienced matlab users. I have some operations to do column by column, I wrote a post for it, please see it here https://se.mathworks.com/matlabcentral/answers/368884-operation-with-big-files
Thank you!
Sean de Wolski
on 7 Sep 2012
x = mat(:,1);
y = mat(:,2);
%etc.
But like Oleg said - don't do it!
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!