Variable assignment in workspace

a=[1,2,3,4,5,6]
b=['c','d','e','f','g','h']
how can i assign the values to the variables that are present in array b and the values of those present in array a without hard coding the variable names.

3 件のコメント

Stephen23
Stephen23 2021 年 8 月 16 日
編集済み: Stephen23 2021 年 8 月 16 日
@vickey vardwaj: do you have a particular reason why you want to force yourself into writing slow, complex, inefficient code?
What exactly are you trying to achieve? If you explain what your ultimate goal is (rather than this anti-pattern, complex, inefficient data design), then we can help you to find a suitable approach (if possible).
vickey vardwaj
vickey vardwaj 2021 年 8 月 16 日
Actually there is a excel sheet with list of variables in one column and list of value in another column. I want to assign those values to the variables in 1st column.
Walter Roberson
Walter Roberson 2021 年 8 月 16 日
Why do you want to do that?
What would you do if the Excel file happened to name a variable that was the same as one of the variable names you were using to code the function?
... If you were to store everything into a struct like I demonstrated, then you would not have any conflicts.

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

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 8 月 16 日

0 投票

The best approach is do not do that
For example, instead
a = [1,2,3,4,5,6]
a = 1×6
1 2 3 4 5 6
b = {'c','d','e','f','g','h'}
b = 1×6 cell array
{'c'} {'d'} {'e'} {'f'} {'g'} {'h'}
output = cell2struct(num2cell(a), b, 2)
output = struct with fields:
c: 1 d: 2 e: 3 f: 4 g: 5 h: 6

2 件のコメント

vickey vardwaj
vickey vardwaj 2021 年 8 月 16 日
Thank Walter for your solution. Actually i wanted the variable to be assigned in the workspace.
Walter Roberson
Walter Roberson 2021 年 8 月 16 日
The best approach is do not do that
If you are not effectively extending the syntax of MATLAB like syms or IBM's cvx, then what you are asking for is more trouble than it is worth, in the long run.

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

カテゴリ

ヘルプ センター および File ExchangeWorkspace Variables and MAT Files についてさらに検索

質問済み:

2021 年 8 月 16 日

コメント済み:

2021 年 8 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by