strontivm
strontivm

Reputation: 59

How to automatically create counter variables in Matlab

I am designing an application that needs to start with no variables at all. But then, at some point, the user will input what he wants to count, say, oranges. Then he will type "oranges". After he writes oranges, I want Matlab to create a variable "orangesCounter". Does anyone have an idea how I can achieve this?

Or maybe someone knows the name for what I am trying to do, if it has a specific name. I just don't know how to properly Google this question since I do not know if there is a name for this type of variable creation.

Thanks!

Upvotes: 0

Views: 1213

Answers (1)

Jonas
Jonas

Reputation: 74930

You're setting yourself up for a huge mess, because how are you going to handle variables with names that aren't known to you in your code? Anyway, it's your foot, so here's the gun:

%# ask for input
varName = input('what do you want to count? Please enclose the word in single quotes.\n')

%# make the corresponding counter variable, initialize it to 0
eval(sprintf('%sCounter=0;'varName'));

Here's a better way to do this:

variables = struct('name','','value','');

%# ask for the first variable
variables(1).name = input('what do you want to count? Please enclose the word in single quotes.\n');

%# ask for how many things there are
variables(1).value = input(sprintf('how many %s are there?\n',variables(1).name));

%# and return feedback
fprintf('There are %i %s.\n',variables(1).value,variables(1).name);

Note the index - you can have multiple name/value pairs in the structure.

Upvotes: 2

Related Questions