How to assign elements in a vector to an entry in a structure array variable?

7 views (last 30 days)
I have an Nx1 structure array which contains a variable:
N = 100;
S(1).Name = 'Jon';
S(2).Name = 'Phil';
S(3).Name = 'Bob';
%etc...
S(N).Name = 'Gary';
I now have an Mx1 vector of values with associated indices which I want to add to a new variable within the structure:
vec = [36 39 21 74];
indices = [6 2 100 17];
S(1).('Age') = []; %initialize new variable in the structure
S(indices).Age = vec; %This is the intuition for what I want to do
However, this gives an error "Assigning to M elements using a simple assignment statement is not supported".
What I want to end up with is:
S(6).Age = 36;
S(2).Age = 39;
S(100).Age = 21;
S(17).Age = 74;
Of course, I could do this with a loop:
for i = 1:length(vec)
S(indices(i)).Age = vec(i);
end
But I want to avoid loops because my code is already within another large loop which is slow.
Any help is appreciated.

Accepted Answer

Matt J
Matt J on 18 May 2023
Edited: Matt J on 18 May 2023
But I want to avoid loops because my code is already within another large loop which is slow.
When dealing with structs, there is no way to improve upon the speed of a loop. However, you can abbreviate the syntax as follows,
vals=num2cell(vec);
[S(indices).Age] = deal(vals{:});

More Answers (2)

Matt J
Matt J on 18 May 2023
Edited: Matt J on 18 May 2023
You could also consider using dictionaries instead of a struct array,
Names=["Jon","Phil","Bob","Gary"];
D=dictionary(Names,nan)
D =
dictionary (stringdouble) with 4 entries: "Jon" ⟼ NaN "Phil" ⟼ NaN "Bob" ⟼ NaN "Gary" ⟼ NaN
vec = [36 74];
indices = [1,4];
D(Names(indices))=vec
D =
dictionary (stringdouble) with 4 entries: "Jon" ⟼ 36 "Phil" ⟼ NaN "Bob" ⟼ NaN "Gary" ⟼ 74

Matt J
Matt J on 18 May 2023
Edited: Matt J on 18 May 2023
You could also consider using a table instead,
Names=["Jon","Phil","Bob","Gary"]';
T=table(Names,nan(size(Names)), 'Var',["Name", "Age"])
T = 4×2 table
Name Age ______ ___ "Jon" NaN "Phil" NaN "Bob" NaN "Gary" NaN
vec = [36 74]';
indices = [1,4]';
T{indices,"Age"}=vec
T = 4×2 table
Name Age ______ ___ "Jon" 36 "Phil" NaN "Bob" NaN "Gary" 74
This can then be converted to a struct array, if desired,
S=table2struct(T)
S = 4×1 struct array with fields:
Name Age

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!