Can MATLAB recognized the name of a variable with input function?

2 ビュー (過去 30 日間)
Ana D Chavez Gonzalez
Ana D Chavez Gonzalez 2021 年 9 月 15 日
編集済み: Stephen23 2021 年 9 月 15 日
I haven't tried yet, but what I want to do is ask the user for an input. For example,
x = input('what is the name of the object?')
The user will only be able to input a certain name of objects. Let's say the user chose milk and in the code milk is as follows:
milk = 30;
Can MATLAB display 30?
Thank you in advance
  1 件のコメント
Stephen23
Stephen23 2021 年 9 月 15 日
編集済み: Stephen23 2021 年 9 月 15 日
"Can MATLAB display 30?"
Yes, but your approach forces you into writing slow, complex, inefficient, obfuscated code which is difficult to debug. Here are two much better approaches, first is to use the fields of a structure (or you can do much the same with a table):
S.beer = [1,2,3];
S.milk = [4,5,6];
x = 'milk'; % user input
S.(x)
ans = 1×3
4 5 6
Second is to simply and very efficiently store the names as data in their own right (which of course as meta-data they are) and then use basic MATLAB indexing:
M = [1,2,3;4,5,6];
C = ["beer","milk"];
M(strcmpi(x,C),:)
ans = 1×3
4 5 6
Understanding that meta-data is data is an important step to writing better code.
Avoiding INPUT means that you can write testable, expandable, callable code.

サインインしてコメントする。

採用された回答

Chunru
Chunru 2021 年 9 月 15 日
It's possible but it should be avoided if possible.
milk = 30;
%x = input('what is the name of the object? ', 's') % use this in your program
x = 'milk'; % for the on-line version
if exist(x, 'var')
eval(x);
else
fprintf('The variable %s does not exist\n', x);
end
milk = 30
  2 件のコメント
Ana D Chavez Gonzalez
Ana D Chavez Gonzalez 2021 年 9 月 15 日
Why should it be avoided? if I may know
DGM
DGM 2021 年 9 月 15 日
編集済み: DGM 2021 年 9 月 15 日
This is a brief explanation
This post explains issues with using eval(), and puts it in context with related topics regarding common usage patterns.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by