How to use structure properly?
Show older comments
Hi all,
I have a newbie question, how to use structural variable properly? A minimum example:
clear; clc;
no.inpt = 5;
inpt.a1 = rand(no.inpt);
inpt.a2 = rand(no.inpt);
inpt.a3 = rand(no.inpt);
[otpt] = teststruct(inpt);
[otpt] = teststruct1(otpt);
where the two functions are:
function [otpt] = teststruct(inpt)
otpt.x = inpt.a1 + 3 * inpt.a2 - inpt.a3;
otpt.y = 2 * inpt.a3;
and
function [otpt] = teststruct1(inpt)
otpt.z = inpt.x * 2 + inpt.y * 3;
After this, variable otpt only contains one subfield z which I understand that teststruct1 regenerate otpt. However, what I want is to let otpt keep three subfields x, y and z without renaming otpt after function teststruct. How could I achieve it?
Many thanks!
2 Comments
@Xh Du: please do not edit your question so that answers do not make sense. This was the original code, where you clearly reallocate the same output variable and do not use it anwhere:
clear; clc;
no.inpt = 5;
inpt.a1 = rand(no.inpt);
inpt.a2 = rand(no.inpt);
inpt.a3 = rand(no.inpt);
[otpt] = teststruct(inpt);
[otpt] = teststruct1(inpt);
Xh Du
on 27 Feb 2017
Accepted Answer
More Answers (1)
Steven Lord
on 27 Feb 2017
In this function:
function [otpt] = teststruct1(inpt)
otpt.z = inpt.x * 2 + inpt.y * 3;
otpt is created anew inside the teststruct1 function when you assign to otpt.z. Since it's a new variable, it only has the fields you explicitly assigned to it. I think you want to make otpt a copy of inpt first before modifying its z field.
function [otpt] = teststruct1(inpt)
otpt = inpt;
otpt.z = inpt.x * 2 + inpt.y * 3;
Categories
Find more on Structures 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!