Azzera filtri
Azzera filtri

Dynamically allocated variables with indices..

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Walter Roberson
Walter Roberson il 18 Giu 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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by