cell row to variable

1 view (last 30 days)
Sidney Smith
Sidney Smith on 13 Apr 2015
Edited: Stephen23 on 19 Jun 2019
I have a cell array of 2 columns - I want to create a cell variable whose name is the ith row of column 1 and whose value is the ith row of column 2 which may be either char or numeric, for example A{i} = 'fred', B[i} = 10 giving Var.fred = 10. sounds simple and I can do it with eval, but I understand use of eval is deprecated - any ideas appreciated
  1 Comment
pfb
pfb on 13 Apr 2015
I was about to suggest using eval... Why is that deprecated?

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 13 Apr 2015
Edited: Stephen23 on 19 Jun 2019

Adam
Adam on 13 Apr 2015
If you mean you want to create a field on a structure with the name of the ith row of column 1 then:
Var.( A{i,1} ) = B{i,1};
should work for your example.
If you really want to create an actual variable I would strong advise against it as it is not good practice.
You can refer to variables very simply in code as e.g. 'A' because you declare them by that exact name somewhere else in the code. If you dynamically create a variable name then you are stuck with dynamically recreating its name every time you want to use it (and all its cohorts you created similarly).
Cell arrays, structs (with dynamic fields) or just normal arrays if it is pure numbers are the best way to achieve this.

Products

Community Treasure Hunt

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

Start Hunting!