Tulkkas
Tulkkas

Reputation: 1013

Extract Matrix columns and store them in individual vectors

I have a A matrix of size MxN where M is large and N is around 30.

[A,B,C,...,AD] = A(:,1:30) 

The reason I am asking that is that I would like to give the columns a specific name (here A,B a,c,...,AD) and not being force to write:

[A,B,C,...,AD] =  deal(A(:,1),A(:,2),A(:,3),...,A(:,30))

Upvotes: 1

Views: 68

Answers (2)

percusse
percusse

Reputation: 3106

For generating that lexicographical sequence I recently, out of ignorance, wrote this

Data = rand(2,671);
r = rem(size(Data,2),26);
m = floor(size(Data,2)/26);
Alf = char('A'+(0:25)'); %TeX-like char seq

if m == 0
    zzz = Alf(1:r);
else
    zzz = Alf;
    for x = 1:m-1
        zzz = char(zzz,[char(Alf(x)*ones(26,1)),Alf]);
    end
    if r > 0
        zzz = char(zzz, [char(Alf(m+1)*ones(r,1)),Alf(1:r)] );
    end
end

Depending on the number of columns it generates column names until ZZ. Please let me know if there is a readily made command for this in matlab.


You would never ever use eval for such things!!! eval use is dangerous and wrong (but you can't resist):

% ========== 
% Assign Data to indices
% ==========

for ind = 1:size(Data,2)
    eval([zzz(ind,:) '= Data(:,' num2str(ind) ');']);
end

and your workspace looks like an alphabet soup.

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

It's usually better to keep all columns together in the matrix and just access them through their column index.

Anyway, if you really need to separate them into variables, you can convert the matrix to a cell array of its columns with num2cell, and then generate a comma-separated list to be used in the right-hand side of the assignment. Note also that in recent Matlab versions you can remove deal:

A = magic(3); % example matrix
Ac = num2cell(A, 1);
[c1 c2 c3] = Ac{:}; % or [c1 c2 c3] = deal(Ac{:});

Upvotes: 1

Related Questions