For loop cycle struct
이전 댓글 표시
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.
답변 (1개)
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
Alias:Max
2019년 1월 26일
편집: Walter Roberson
2019년 1월 28일
Steven Lord
2019년 1월 27일
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
2019년 1월 28일
See also new question here:
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!