Dynamically allocated variables with indices..
2 views (last 30 days)
Show older comments
Robert
on 17 Jun 2015
Answered: Walter Roberson
on 18 Jun 2015
Hello folks,
Quick question. I need to dynamically allocate variables from a cell array using a string value within the cell.. I know it is not good practice to use eval but my application requires me to do this. The expression I require to be evaluated is:
eval(sprintf('%s = ''%s''',cell2mat(stocks(i,1)),cell2mat(C(1,k))))
- which has the output: AAVL = 300
However I need the output: AAVL(j,k) = 300
I am having trouble adding indices..
When I try this:
eval(sprintf('%s(%d,%d) = ''%s''',cell2mat(stocks(i,1)),j,k,cell2mat(C(1,k))))
which gives an error: Assignment has more non-singleton rhs dimensions than non-singleton subscripts
note:
cell2mat(stocks(i,1)) % yields the AAVL string
cell2mat(C(1,k))) % yields the value 300 which was initially a string
Any help would be much appreciated!
0 Comments
Accepted Answer
Walter Roberson
on 18 Jun 2015
allvars.(stocks{i,1})(j,k) = str2double(C{1,k}));
That is, do not use eval, do not generate variable names on the fly. Use dynamic field names on a structure. Eventually you may need to save the structure as individual variables; you can do that with
save('AppropriateFilename.mat', 'allvars', '-struct')
which will create one variable in the .mat file for each field of structure allvars.
0 Comments
More Answers (0)
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!