Function not outputting structure array
1 次查看(过去 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!