Contenuto principale

Concatenazione di strutture

Questo esempio mostra come concatenare gli array di strutture utilizzando l'operatore []. Per concatenare le strutture, è necessario che abbiano lo stesso insieme di campi, ma i campi non devono necessariamente contenere dati delle stesse dimensioni o dello stesso tipo.

Creare array di strutture scalari (1x1) struct1 e struct2, ciascuno con i campi a e b:

struct1.a = 'first';
struct1.b = [1,2,3];
struct2.a = 'second';
struct2.b = rand(5);
struct1,struct2
struct1 = struct with fields:
    a: 'first'
    b: [1 2 3]

struct2 = struct with fields:
    a: 'second'
    b: [5×5 double]

Proprio come concatenando due valori scalari come [1,2] si crea un array numerico 1x2, concatenando struct1 e struct2 si crea un array di strutture 1x2.

combined = [struct1,struct2]
combined=1×2 struct array with fields:
    a
    b

Quando si desidera accedere al contenuto di un campo specifico, specificare l'indice della struttura nell'array. Ad esempio, accedere al campo a della prima struttura.

combined(1).a
ans = 
'first'

La concatenazione si applica anche agli array di strutture non scalari. Ad esempio, creare un array di strutture 2x2 denominato new. Poiché sia la struttura 1x2 combined che la struttura 2x2 new hanno due colonne, è possibile concatenarle verticalmente con un separatore punto e virgola.

new(1,1).a = 1;
new(1,1).b = 10;
new(1,2).a = 2;
new(1,2).b = 20;
new(2,1).a = 3;
new(2,1).b = 30;
new(2,2).a = 4;
new(2,2).b = 40;

larger = [combined; new]
larger=3×2 struct array with fields:
    a
    b

Accedere al campo a della struttura larger(2,1). Contiene lo stesso valore di new(1,1).a.

larger(2,1).a
ans = 
1

Vedi anche

Argomenti