Multiplying structures together based on field names
Show older comments
Is there any method to multiply structures together according to their field names? For example,
struct1.a=1;
struct1.b=2;
struct2.a=3;
struct2.b=4;
And the result would be:
struct3.a=3
struct3.b=8
1 Comment
Note that storing sets of data in one variable makes more sense than lots of sequentially-named variables, and simplifies the code significantly over creating and using dynamically named variables. You might like to read this to learn some of the reasons why:
This is what David Young proposes in their second solution, and you should seriously consider using a non-scalar structure to store your data rather than multiple individual variables.
Accepted Answer
More Answers (1)
Jonathan Campelli
on 9 Apr 2015
Hello Oliz,
I've played around with your structures, and I have multiplied struct1.a through struct2.b in the following way:
struct1.a=1
struct1.b=2
struct2.a=3
struct2.b=4
struct3.a=struct2.a*struct1.a %The multiplication operator provides the right solution.
struct3.b=struct2.b*struct1.b
Once run, the script yields the following results:
struct1 =
a: 1
struct1 =
a: 1
b: 2
struct2 =
a: 3
struct2 =
a: 3
b: 4
struct3 =
a: 3
struct3 =
a: 3
b: 8
Keep having fun with these things.
Best regards,
Jonathan Campelli
3 Comments
Oliz
on 9 Apr 2015
Jonathan Campelli
on 9 Apr 2015
I see. You may find this solution to a related scenario more applicable: http://www.mathworks.com/matlabcentral/answers/66780-multiply-each-element-of-structured-array-assignment-of-structured-array.
Oliz
on 9 Apr 2015
Categories
Find more on Data Preprocessing 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!