Effacer les filtres
Effacer les filtres

How to Change Values of a Field by an Indexing Array?

3 vues (au cours des 30 derniers jours)
Rightia Rollmann
Rightia Rollmann le 12 Mar 2017
Modifié(e) : Jan le 13 Mar 2017
Here’s my initial struct:
A(1).B.C = 'a';
A(2).B.C = 'b';
A(3).B.C = 'a';
A(4).B.C = 'a';
I want to change the values of C based on values of Values and indexes of IndexingArray:
Values = {'a', 'b'}
IndexingArray = [1 1 0 1];
So, my struct will be:
A(1).B.C = 'b';
A(2).B.C = 'b';
A(3).B.C = 'a';
A(4).B.C = 'b';
What is the solution?

Réponse acceptée

Chad Greene
Chad Greene le 12 Mar 2017
You could change each element individually via loop. But make sure you add 1 to the indexing array values because Matlab starts indexing at 1, not 0.
for k = 1:length(A)
A(k).B.C = Values(IndexingArray(k)+1);
end
  3 commentaires
Jan
Jan le 13 Mar 2017
Modifié(e) : Jan le 13 Mar 2017
@Rightia Rollmann: The nested struct is a complicated method to represent data. In consequence the method to access the values is not trivial anymore. This loop is efficient and compact. (+1)
Assumingly a typo:
A(k).B.C = Values{IndexingArray(k)+1}; % Curly braces
Chad Greene
Chad Greene le 13 Mar 2017
Ah, yes, curly braces. Thanks for catching that Jan!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Resizing and Reshaping Matrices 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