using vertcat to convert a number of variables in the workspace into a column vector
3 views (last 30 days)
Show older comments
Hi,
I have a number of variables in my workspace that I believe are arrays, each contain just one single value, and I am trying to organise them into a single column vector.
However when i try to use the vertcat function I am faced with a problem. The variables in my workspace are called P1,P2,P3,P3,....,P1650 and when I use the function: vertcat(P1:P1650) it just produces a 1 x 0 empty double row vector. But when I type in individual variables e.g. vertcat(P1,P2,P3,P4,P5,P6,P7,etc) it concatenates them as I would like.
Does anyone know what I am doing wrong here?
many thanks!
1 Comment
Stephen23
on 12 Feb 2017
Edited: Stephen23
on 13 Feb 2017
"The variables in my workspace are called P1,P2,P3,P3,....,P1650"
How did they get there? Although there are hack-fixes using eval to resolve the bad idea of having lots of numbered variables, the best solution is to avoid this whole problem altogether, e.g. if you simply load into a structure.
"Does anyone know what I am doing wrong here?": acessing variable names dynamically will be slow, buggy, obfuscated code. You should read this:
Answers (1)
Star Strider
on 12 Feb 2017
You have a problem that you didn’t create, know as ‘dynamically named variables’. I don’t know from your description if they are arrays or single values. The eval function can put things back to rights and create your vertically-concatenated array:
For single values —
[P1,P2,P3,P4,P5] = deal(1,2,3,4,5); % Assign Variables
for k1 = 1:5
C(k1,:) = eval(sprintf('P%d', k1)); % Create Column Vector
end
For arrays of possibly different sizes —
for k1 = 1:5
C{k1,:} = eval(sprintf('P%d', k1)); % Vertically-Concatenated Cell Array
end
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!