Loading structs into a script from the Workspace

17 views (last 30 days)
Hey there! I am trying to load some structs already imported into my workspace. I created a script that makes all the operations I need to each struct loaded. Now I need to create an algorithm that allows me to apply this script to every struct imported. I was considering using a FOR since the names are sequences (Struct_1, Struct_2, Struct_3...) (I thought I could use a variable Struct_i, where i=0:'number o structs I want to load') but I am not sure if I can use the function LOAD for this operation. I am sorry if this is a dumb question, I am just starting with Matlab. Thank you!!

Answers (1)

Ameer Hamza
Ameer Hamza on 5 Dec 2020
Edited: Ameer Hamza on 5 Dec 2020
This is not a dumb question; it highlights one of the common mistakes which new programmer make, i.e., creating variable names like var1, var2, var3, ... Then they run into a problem which you mentioned in your question. This thread: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval have a very useful discussion on this topic.
The correct way to handle such cases is to use arrays. For example, if all of your structs contain the same fields, you can create a struct array like this (a good approach is to create an array from the beginning, however, since you already have these variables, you can now create an array)
struct = [struct1, struct2, struct3, ..]; % write down the name of all the struct variables
Now you will see the thing will become so easy. You can create a for-loop and apply the same code to all the elements in the array
for i = 1:numel(struct)
s = struct(i);
% apply code to s
end
The for loop will iterate over the entire array and apply the code to each struct.
In case, each struct have different fields, you can create a cell array
struct = {struct1, struct2, struct3, ..}; % write down the name of all the struct variables
and the for-loop will be like this
for i = 1:numel(struct)
s = struct{i};
% apply code to s
end

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!