How to use index for structure within for loop?

31 vues (au cours des 30 derniers jours)
shatha almarri
shatha almarri le 17 Fév 2021
Modifié(e) : Stephen23 le 17 Fév 2021
I have 4 structures s1,s2,s3, and s4 ... all have .time and .disp within each structure
I am trying to make a for loop that will do something like this ie: use an index i and run the loop four times, saving the output of a function in a new structure each time (M1, M2, M3 and M4), so I want the i in the following loop to be replaced by 1-4 each time. I am unsure of how to do this as of now my code is thinking the structure name is s not s1,s2,s3,s4 ... I have tried using [] and {} but I get errors
for i = 1:4
[speed, acc] = CalculateFunction [s(i).time, s(i).disp] %when i = 1 this line will be =CalculateFunction [s1.time, s1.disp]
M(i) = struct % when i = 1 this line will be M1.struct and so on..
M(i).speed = speed
M(i).acc = acc
end

Réponses (1)

Stephen23
Stephen23 le 17 Fév 2021
Modifié(e) : Stephen23 le 17 Fév 2021
Using numbered variable names is a sign that you are doing something wrong.
The simple and efficient approach is to use one non-scalar structure:
s = [s1,s2,s3,s4];
for s = 1:4
s(k)
end

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by