Dynamically allocated variables with indices..

2 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2015-6-18
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 个)

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by