Make Field of certain size in structure using a loop

Dear everyone,
I am stuck with a possibly trivial problem.
I want to create a structure that has N number of fields named X1,X2,...XN. Each of those X1,X2,...XN are of some size S, such that X1 is a field of dimensions 1xS.
This is a minimal (not) working example:
batch_list = {'batch1','batch2'};
data = [];
S = 400
for i = 1:length(batch_list)
for j = 1:S
images.(batch_list{j,i}) = {X(j)};
end
end
For i = j = 1 I get a structure called images, with a 1x1 field called batch1. So far so good.
For i = 1 and j = 2 I get a error message "Index exceeds matrix dimensions" because the field is 1x1, and therefore cannot accept j = 2. I've tried redefining the size of the field in the structure, but it gets overwritten by my code.
I am lost as how to correct this and would appreciate any input.
Thank you.

1 comentario

Use a non-scalar structure, this will be a lot simpler:
>> A(1).batch = 1:3;
>> A(2).batch = 4:6;
>> A(3).batch = 7:9;
and there are lots of easy ways to access the data:
>> A(2).batch
ans =
4 5 6
>> vertcat(A.batch)
ans =
1 2 3
4 5 6
7 8 9

Iniciar sesión para comentar.

 Respuesta aceptada

Guillaume
Guillaume el 13 de Jul. de 2016
Your batch_list is a 1x2 cell array, therefore, in batch_list{j, i}, the maximum acceptable value for j is 1 and the maximum acceptable value for i is 2. Your j index is not meant to iterate over the names of the fields, but over the content of the field, so move it out of the name expression:
images.(batch_list{i}){j} = {X(j)};
It's not clear what X is and why you'd want to replicate it in two different fields (possibly you meant X(i, j) ?) but a more efficient way to generate the full structure would be simply with cell2struct.
Reproducing the exact same output as your code:
images = cell2struct([X(:), X(:)]', batch_list, 1)
%if X is a 1xS cell array, the expression in brackets could simply be [X; X]
%the above will work regardless of the shape of X (1xS, Sx1, MxN)
If X is already a 2xS cell array:
images = cell2struct(X, batch_list, 1)

2 comentarios

Thanks for your input. Moving {j} outside solved my problem. My example is simplified, so it is feed through a function that returns a mix of strings and integers, thus cell2struct would not work optimally for me.
Guillaume
Guillaume el 13 de Jul. de 2016
The only difference between a structure array and a cell array is that with a structure array one dimension is labeled (the field names).
You can swap between one format and the other with cell2struct and struct2cell without affecting any of the data stored. It stays where it is in memory.
Thus, there is no reason why cell2struct would not work optimally.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 13 de Jul. de 2016

Comentada:

el 13 de Jul. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by