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!