Function not outputting structure array
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Matt J
le 25 Avr 2018
Modifié(e) : Matt J
le 25 Avr 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 commentaires
Stephen23
le 25 Avr 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
le 25 Avr 2018
Modifié(e) : Matt J
le 25 Avr 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!