Effacer les filtres
Effacer les filtres

Using a programmed struct name as function argument or programming pressing "enter" in the command window

2 vues (au cours des 30 derniers jours)
I am trying to use a struct as an argument for my function:
[Output] = Function(InputString);
I have programmed the form of the "InputString", using
InputString = ['SomeText(' num2str(SomeNumber) ').SomeText.m' month 'd' day 't' time];
which returns a character array. When copying and pasting the result of "InputString" into the command window and pressing enter, the desired field of the struct is correctly read. However, with the code above, MATLAB only using the text of "InputString" as an input and not the desired struct that it represents.
How do I program copying the result of "InputString" and entering it in the command window, or is there a nicer solution?

Réponse acceptée

Guillaume
Guillaume le 9 Mar 2018
Modifié(e) : Guillaume le 9 Mar 2018
As per Walter's comment dynamic naming of variables is a bad idea. However, in you case, it's the fields of the structure that are dynamic so it's less of a problem.
The crux of your issue is that the list of argument to a function is not a string. It's the actual content of a variable, which is of course not what you're passing. When you copy/paste that string you've built at the command prompt, you're actually evaluating it. That's why it works. You could do the same in your code, evaluate the string but do not do that as there is a much better way:
output = Function(SomeText(SomeNumber).SomeText.(sprintf('m%dd%dt%d', month, day, time)))
I'm assuming month, day, time are integers here and using sprintf to build the field name instead of string concatenation, but the important bit is that the dynamic field name is given using (). See Generate field names from variables.

Plus de réponses (0)

Catégories

En savoir plus sur Structures 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!

Translated by