Effacer les filtres
Effacer les filtres

create structure variable within loop using strings??

11 vues (au cours des 30 derniers jours)
Michael
Michael le 17 Juin 2015
Modifié(e) : Stephen23 le 29 Juin 2015
within a loop I would like to do something along the lines of the following:
for dive = 1:10
for n = 1:3
(['data_split(',num2str(dive),').n',num2str(n),'.var']) = var;
end
end
so that I end up with a structure like:
data_split(1).n1.var for n= 1:3 and dive = 1:10
  3 commentaires
Michael
Michael le 17 Juin 2015
anyone got ideas?
Stephen23
Stephen23 le 17 Juin 2015
Modifié(e) : Stephen23 le 29 Juin 2015

Connectez-vous pour commenter.

Réponse acceptée

Alberto
Alberto le 17 Juin 2015
Modifié(e) : Alberto le 17 Juin 2015
for dive = 1:10
for n = 1:3
data_split(dive).( ['n',num2str(n)]).('var')=var
end
end

Plus de réponses (1)

Stephen23
Stephen23 le 17 Juin 2015
Modifié(e) : Stephen23 le 18 Juin 2015
This is easy with a bit of help from the documentation, but first we have to understand that these are two separate operations that we are trying to do. Lets look at them:
1) Indexing of a Non-Scalar Structure. Just like any array in MATLAB a structure can be non-scalar, and is indexed using logical or subscript indexing:
>> A(3).data = 9;
>> A(2).data = 3;
>> A(1).data = 1
A =
1x3 struct array with fields:
data
>> [A.data]
ans =
1 3 9
You can use all the usual indexing methods here, plus some very handy shortcuts: check out the link I gave above.
2) Using Dynamic Fieldnames to define or access structure fields. These are also written using parentheses:
>> B.('data') = 2;
>> B.('another_field') = 4
B =
data: 2
another_field: 4
Combining These...
So we can easily combine these two operations like this:
for dive = 1:10
for n = 1:3
tmp = sprintf('n%d',n);
data_split(dive).(tmp).var = XXX;
end
end
Note that using sprintf is usually a more robust way to construct strings, compared to string concatenation. It also makes the intent clearer, as the sequence is clearly defined in the format string.
PS: using eval to generate variable names or perform basic operations in MATLAB really should avoided. Although beginners seem to love variables magically appearing an disappearing from workspace it is not a robust way to program and only makes their own lives more difficult. Read this to know more:

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by