For loop cycle struct
2 views (last 30 days)
Show older comments
i have a struct which consist of 10 sets of data, i.e struct(1), struct(2).......
I need to extract certain bits of data from each data set to use in a formula.
as an example:
struct(1).Mass = 200 struct(1).Distance=50
struct(2).Mass = 350 struct(2).Distance=100
struct(3).Mass = 400 struct(3).Distance=150
now if i had an equation such as: if struct(1) %<<<<<<The user selects their struct
Mass1=200
Mass2=(i) %<< this cycles and presents all the possibilities for Mass. i.e 350, 400
similar with distance. If struct(1)
Distance1=50
Distance2=(j) %<<<<<<This cycles and presents all possibilities for Distance. i.e 100, 150
If the equation was: (Mass1 * Mass2) / (Distance 1 - Distance 2).
How can i make it loop so that it presents all of the output as a list. such as:
input(struct(1))
(200 * 350) / (50 - 100) = -1400
(200 * 400) / (50 - 150) = -800
As i stated i would have 10 of these lines. the example scenario is to help me grasp the concept of whats needed to implement a loop system that presents the list of solved equation as shown above.
I would appreciate any help regarding this.
0 Comments
Answers (1)
Stephen23
on 26 Jan 2019
Edited: Stephen23
on 26 Jan 2019
This is MATLAB, so it is simpler to avoid using a loop:
>> S(1).Mass = 200; S(1).Dist=50;
>> S(2).Mass = 350; S(2).Dist=100;
>> S(3).Mass = 400; S(3).Dist=150;
>> idx = 1; % user selected index.
>> idv = setdiff(1:numel(S),idx);
>> num = (S(idx).Mass * [S(idv).Mass]);
>> den = (S(idx).Dist - [S(idv).Dist]);
>> out = num ./ den
out =
-1400 -800
Read about how this works:
3 Comments
Steven Lord
on 27 Jan 2019
I would instead store the data in a table array with appropriate RowNames. See for example the "Specify Row Names" example on the table documentation page for an illustration of how to set and use row names.
Stephen23
on 28 Jan 2019
See also new question here:
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!