How to use structure properly?
이전 댓글 표시
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
@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
2017년 2월 27일
채택된 답변
추가 답변 (1개)
Steven Lord
2017년 2월 27일
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;
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!