How can I use the content of a variable to call another variable?

I'm confronted with the following problem:
eur2usd =[ 1.3 1.2 1.1];
eur2cad =[0.8 0.9 0.7];
currency = 'eur2usd'
I would like to use the variable currency to call the content of eur2usd ([ 1.3 1.2 1.1]). So that if currency = 'eur2cad', I can call the content of eur2cad by using the variable currency.

2 件のコメント

Adam
Adam 2014 年 8 月 18 日
I would favour coming up with a solution which didn't require you to do that. e.g. having currency be a function handle rather than a raw variable-name string, or using containers.Map or some kind of array to index into.
But if you are set on having a variable name in a string I'm sure someone can soon furnish you with the appropriate eval-based syntax.
Stephen23
Stephen23 2015 年 1 月 4 日
編集済み: Stephen23 2023 年 9 月 12 日
Basically you should not do this.
Using dynamically defined variable names or encoding data within the variable name is a pretty bad approach:
You should probably be using for your data: structures. This shows how it could work:
>> A = struct('eur2usd',[ 1.3 1.2 1.1],'eur2cad',[0.8 0.9 0.7]);
>> A.('eur2cad')
ans = [0.8,0.9,0.7]
Note that using a structure is extendable to any number of currencies without cluttering-up your workspace with a thousand variables. There is also a large selection of tools that you can use to manipulate structures, their fields and contents:
Summary: do not use eval to encode (meta-)data into the variable names!

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

 採用された回答

Andrew Reibold
Andrew Reibold 2014 年 8 月 18 日
編集済み: Andrew Reibold 2014 年 8 月 18 日

0 投票

eval(currency)
or
eval('eur2usd')
etc

1 件のコメント

Image Analyst
Image Analyst 2015 年 1 月 4 日
David's "Answer" moved here since it'a not an Answer to the origianl question but a reply to Andrew
Thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2014 年 8 月 18 日

編集済み:

2023 年 9 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by