Function not outputting structure array
조회 수: 8 (최근 30일)
이전 댓글 표시
Let's say I have a script which prompts the user for a certain variable to be loaded in. Let's call these variables a, b, or c. Something like:
varname = 'What variable would you like to load? ';
varname = input(varname,'s');
I then call a function to do some calculations:
func1(varname)
Within func1, I do some calculations, and then want to output this to a structure array:
array1.varname = datathatIcalculated
The overarching script looks like the following:
varname = 'What variable would you like to load? ';
varname = input(varname,'s');
func1(varname)
However, instead of getting array1.varname as an output, I end up only getting a variable 'ans' which is a structure field with varname as a field, so it looks like ans.varname. Why am I not getting array1.varname as an output?
댓글 수: 0
채택된 답변
Matt J
2018년 4월 25일
편집: Matt J
2018년 4월 25일
When you invoke func1(), assign its output to something in that workspace.
varname = input('What variable would you like to load? ','s');
array1=func1(varname)
Otherwise, it goes to ans by default.
댓글 수: 3
Stephen23
2018년 4월 25일
"Now what if I wanted to loop through? For example, I now had 2 varnames and wanted them to all be put inside the array1?"
Do NOT try to access different names in a loop, just use one variable and indexing. How to use indexing is a basic MATLAB concept that is explained in the introductory tutorials:
Matt J
2018년 4월 25일
편집: Matt J
2018년 4월 25일
For example, I now had 2 varnames and wanted them to all be put inside the array1?
Instead of passing variable names to func1, I would pass a template struct with empty fields. For example, solicit all your variable names as follows,
for i=1:N
varname = input('What variable would you like to load? ','s');
S.(varname)=[];
end
and then fill all the empty fields of S within func1 as follows,
function S=func1(S)
f=fieldnames(S);
for i=1:numel(f)
switch f{i}
case 'var1'
S.('var1')=ComputeSomething();
case 'var2'
S.('var2')=ComputeSomethingElse();
...
otherwise
error 'Unrecognized variable name'
end
end
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!