using vertcat to convert a number of variables in the workspace into a column vector
조회 수: 3 (최근 30일)
이전 댓글 표시
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
Stephen23
2017년 2월 12일
편집: Stephen23
2017년 2월 13일
"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:
답변 (1개)
Star Strider
2017년 2월 12일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!