필터 지우기
필터 지우기

How to assign a structure with fields (incl the values in the fields) as an output in function?

조회 수: 2 (최근 30일)
Hello,
My question is the following: How to assign a structure with fields (incl the values in the fields) as an output in function?
Let's say the code is something like this
function output =example(x)
struct(1).field1=x+1
struct(2).field1=x+2
struct(1).field2=x/5
struct(2).field2=x/6
output=struct(1:2)
_________________
How do I assign the fields with their values to the output variable. In this example here I have two fields, but in the actual function I have a lot more and all of these fields have values which I would like to use later in the workspace.
Any ideas?
  댓글 수: 2
Jos (10584)
Jos (10584) 2016년 6월 21일
do not use a keyword or function name ( _ struct_) as a variable name. You can easily avoid this using a variable name like MyStruct.
lou
lou 2016년 6월 21일
Sorry for the confusion - in the actual script I am not using the keywords. My structure and fields have names different from keywords.
Do you have any idea how to solve the issue with getting the whole structure with its fields and values as an output?

댓글을 달려면 로그인하십시오.

채택된 답변

Jos (10584)
Jos (10584) 2016년 6월 21일
function Sout = myfunction(x)
S(1).field(1) = x ;
S(2).field(2) = 2*x ;
% etc.
Sout = S ; % just copy
% end of my function
Do not use names like field1, field2, but use an array (of doubles, cells or even structs)!!!
  댓글 수: 4
Jos (10584)
Jos (10584) 2016년 6월 21일
well done! Field names like Name and Credit are good names, of course.
Stephen23
Stephen23 2016년 6월 21일
편집: Stephen23 2016년 6월 21일
@lou: you don't even need to make it that complicated. Simply put the name of the structure as the output argument, without assigning it to another variable:
function S = myFun()
S.name = ...
S.age = ...
end
It is not required to do output = S; anywhere.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by