Effacer les filtres
Effacer les filtres

Creating variables consisting of many elements

3 vues (au cours des 30 derniers jours)
Gratitude Kim
Gratitude Kim le 4 Août 2017
Commenté : Andrei Bobrov le 4 Août 2017
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 commentaires
Stephen23
Stephen23 le 4 Août 2017
Modifié(e) : Stephen23 le 4 Août 2017
@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:
Gratitude Kim
Gratitude Kim le 4 Août 2017
Thanks for your assistance.

Connectez-vous pour commenter.

Réponses (3)

Daniel Burke
Daniel Burke le 4 Août 2017
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 le 4 Août 2017
Or the undocumented function sprintfc:
sprintfc('X%d', 1:10)

Philip Borghesani
Philip Borghesani le 4 Août 2017
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))

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by