Function not outputting structure array

1 view (last 30 days)
Simpson
Simpson on 25 Apr 2018
Edited: Matt J on 25 Apr 2018
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?

Accepted Answer

Matt J
Matt J on 25 Apr 2018
Edited: Matt J on 25 Apr 2018
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 Comments
Stephen23
Stephen23 on 25 Apr 2018
"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
Matt J on 25 Apr 2018
Edited: Matt J on 25 Apr 2018
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

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!