Borrar filtros
Borrar filtros

Automatically creating and editing Fields of struct with for Loop

33 visualizaciones (últimos 30 días)
That is my current code:
%%Struct Problem
for k=1:5
struct.i(k).m=rand;
struct.i(k).n=rand;
struct.i(k).o=rand;
struct.i(k).p=rand;
struct.i(k).q=rand;
end
And I want to automate the steps in a way like this:
for k=1:5
for a=['m','n','o','p','q']
struct.i(k).a=rand;
end
end
How can I automatically create and edit fields with a for loop?

Respuesta aceptada

Image Analyst
Image Analyst el 17 de Dic. de 2016
What's wrong with the first way? That's the method I'd prefer. It's much more straightforward and intuitive and easy to understand than using dynamic field names.
I really don't recommend dynamic field names, but if you insist, it is possible, though a lot more complicated than your first method:
% Initialize just one struct with 5 fields.
s = struct('m',0, 'n',0, 'o',0, 'p',0, 'q',0)
letters = {'m', 'n' 'o','p','q'}
size(s)
% Now make an array of 10 of them.
myStruct = repmat(s, 1, 10) % Whatever
size(myStruct)
for k = 1 : size(myStruct, 2)
for lIndex = 1 : length(letters)
fprintf('Assigning field %s to structure #%d\n', letters{lIndex}, k)
myStruct(k).(letters{lIndex}) = rand;
end
end
  3 comentarios

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by