Create structs with different number of columns

Hi.
Assume that I have a parameter n, that has no constant value.
I want to cretae a single structure with n columns and m rows (m is constsnt) in each iteration of a loop. How can I do this? Note that in each loop, the parameter n is changed, so, the structures have no constant column.
Thanks in advance.

Respuestas (1)

This is not possible if you are referring to struct array and columns refers to the second dimension. For example if you had
s = struct('hello', 5);
s(1,5).hello = true;
Then you could not say that for s(2,:) you only want 3 columns.
You could store each struct inside a cell array.

5 comentarios

civil tech
civil tech el 4 de Nov. de 2020
Editada: civil tech el 4 de Nov. de 2020
Thank you.
My exact question can be seen as an example below:
Assume that, n = 4. If the names of fields have been defined before as (a,b,c,d), it means that the structure STR has four columns of STR.a, STR.b, STR.c and STR.d.
My problem is that, the n is not constant. Therefore, I can't define (a,b,..) because I don't know how many names is needed for the STR.
That question is incorrect. That is a scalar struct with four fields.
If you do not know n ahead of time then
fn = cellstr(char(randi(26,n,10)+'a'-1)))
Now you have n different field names and can assign to them using dynamic fields
s.(fn{K}) = "this is field " + K
civil tech
civil tech el 4 de Nov. de 2020
Many thank. What is K here?
When you want to access the K'th field, then fn{K} holds its name.
The code might be rather different if you had a small maximum bound on n making it practical to define allowed field names in advance
civil tech
civil tech el 4 de Nov. de 2020
Thank you so much.

Iniciar sesión para comentar.

Categorías

Etiquetas

Preguntada:

el 4 de Nov. de 2020

Comentada:

el 4 de Nov. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by