0

変数をまったく使用せずに開始する必要があるアプリケーションを設計しています。しかし、ある時点で、ユーザーは数えたいもの、たとえばオレンジを入力します。次に、彼は「オレンジ」と入力します。彼がオレンジを書いた後、Matlab に変数「orangesCounter」を作成してもらいます。どうすればこれを達成できるか考えている人はいますか?

または、特定の名前がある場合、誰かが私がやろうとしていることの名前を知っているかもしれません。このタイプの変数作成に名前があるかどうかわからないため、この質問を適切にグーグルする方法がわかりません。

ありがとう!

4

1 に答える 1

2

コード内で知らない名前の変数をどのように処理するのでしょうか? とにかく、それはあなたの足なので、ここに銃があります:

%# 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'));

これを行うより良い方法は次のとおりです。

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);

インデックスに注意してください。構造には複数の名前と値のペアを含めることができます。

于 2012-11-05T23:15:46.920 に答える