Creating variables consisting of many elements

I want to create a variable consisting of X1 to X10 . Is there an easy way instead of typing X1 to X10?
V1={'X1','X2','X3','X4','X5','X6','X7','X8','X9','X10'}
Thanks

댓글 수: 3

Your problem is upstream, and is a great illustration of why it is almost always a terrible idea to name variables X1, X2, etc.
Can you fix that prior code, to use a vector with elements X(1), X(2), or a cell array with elements X{1}, X{2}, etc?
If that is impossible, there are still solutions to your awkward problem, via even more awkward methods. What is the class and size of X1, etc?
Stephen23
Stephen23 2017년 8월 4일
편집: Stephen23 2017년 8월 4일
@Gratitude Kim: what do you need these string for? The best solution may well depend on your usecase.
>> arrayfun(@(n)sprintf('X%d',n),1:10,'uni',0)
ans =
'X1'
'X2'
'X3'
'X4'
'X5'
'X6'
'X7'
'X8'
'X9'
'X10'
or perhaps
>> regexp(sprintf('X%d ',1:10),'\S+','match')
If you are planning on accessing variables with those names then DON'T. Read this to know why:
Thanks for your assistance.

댓글을 달려면 로그인하십시오.

답변 (3개)

Daniel Burke
Daniel Burke 2017년 8월 4일

1 개 추천

From your question it looks like you want V1 to be a cell array of strings, ranging from 'X1' to 'X10', this code should do the trick if that is your goal:
V1 = cell(1,10)
for i = 1:10
V1{i} = ['X' num2str(i)]
end
Jan
Jan 2017년 8월 4일

1 개 추천

Or the undocumented function sprintfc:
sprintfc('X%d', 1:10)
Philip Borghesani
Philip Borghesani 2017년 8월 4일

1 개 추천

If you don't mind strings and have R2017a I like:
"x"+(1:10)
Or if you want a cell array or have 2016b:
cellstr(string('x')+(1:10))

카테고리

도움말 센터File Exchange에서 App Building에 대해 자세히 알아보기

태그

질문:

2017년 8월 4일

댓글:

2017년 8월 4일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by