Function not outputting structure array
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Matt J
am 25 Apr. 2018
Bearbeitet: Matt J
am 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 Kommentare
Stephen23
am 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
am 25 Apr. 2018
Bearbeitet: Matt J
am 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!