Is there an efficent way to assign names to the vectors in a matrix

11 views (last 30 days)
I would like to assign a vector of names to the vectors of a matrix. I have the data in a matrix, but I need to be able to access it as vectors using predetermined names. I have the following vector of variables:
[TIM PAN STAT VB VR IBI] (shorted for convenience)
and a Nx6 data matrix. I want to assign each of the column vectors in this data matrix to the variable in the corresponding row of the variable matrix.
bei. TIM=data(:,1), PAN=data(:,2) etc
these don't work
[TIM PAN STAT VB VR IBI]=data;
or ...
for i=1:size(names,2)
names(i)=result(:,i);
end
Any help is appreciated. I always seem to run into this kind of problem when I try and work with other peoples code :(

Accepted Answer

Walter Roberson
Walter Roberson on 1 Nov 2011
t = mat2cell(data, size(data,1), ones(1,size(data,2)));
[TIM PAN STAT VB VR IBI] = deal(t{:});
Note: this will make copies of the data matrix as of the time it is executed. If you need to have the data matrix keep in sync as you change elements of your named columns, then you will need to write a OOP class.
I find that in the cases I have encountered, it has often been sufficient to take a different approach:
t = num2cell(1:size(data,2));
[TIM PAN STAT VB VR IBI] = deal(t{:});
and then thereafter instead of referring directly to TIM as a vector, instead refer to data(:,TIM) . This keeps the data in the original matrix and continues to allow you to do things like
data(12:19,STAT) = 0;
while keeping the array synchronized so you can still do things like
data(23,:)
to refer to the current values of what is stored for the 23rd sample.
  3 Comments
Walter Roberson
Walter Roberson on 1 Nov 2011
Well, yes, if you have a sufficiently new version of MATLAB. I prefer not to count on new-fangled inventions.
(Well... it is more that I consider it to be a bad syntactic structure and I prefer to future-proof my code against the day when Mathworks realizes the mistake and withdraws the syntax ;-) )

Sign in to comment.

More Answers (1)

Jan
Jan on 1 Nov 2011
If the list of names can be changed dynamically:
Do not do this. It is not efficient and prone to errors. See: Wiki: Create A1,A2,... in a loop.
You can use a struct with dynamic fieldnames instead:
Names = {'TIM', 'PAN', 'STAT', 'VB', 'VR', 'IBI'};
for i = 1:numel(names)
Data.(names{i}) = result(:, i);
end
disp(Data.TIM);
If the list of names is fixed, see Walter's answer.

Categories

Find more on Characters and Strings 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!