how to write variables in a functions workspace by assignin

17 ビュー (過去 30 日間)
Muge Erinc
Muge Erinc 2013 年 2 月 4 日
回答済み: Jan 2014 年 1 月 11 日
Hello,
I would like to create annotation objects in a functions local workspace, where object names are created in a loop.
here is how I would like to code to look:
x_ini = 0.27;
for k=1:6
dummy = annotation(f,'textbox','EdgeColor', 'white', ...
'String',mycell(:,k),'Position',[x_ini 0.34 0.11 0.15],...
'BackgroundColor','white','Visible','on');
x_ini = x_ini+ 0.08;
assignin('??ws??',['h_ann_' num2str(k)], dummy)
end
When I use eval, this error pops: attempt to write a variable to a static workspace.
With evalin or assingin, I cannot find how to name the functions local workspace. opening up the loop works, however it is ugly: h_ann1 = ... h_ann2 = ...
Thanks in advance, Muge
  1 件のコメント
Muthu Annamalai
Muthu Annamalai 2013 年 2 月 23 日
Alternatively, you may want to create a static object like 'containers.Map' and store the string-value associations.

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

採用された回答

Alec
Alec 2014 年 1 月 11 日
To use `assignin` inside a function try:
feval(@()assignin('caller',['h_ann_' num2str(k)], dummy));
This temporarily creates an anonymous function around `assignin` and then calls it. Effectively making your function the "caller".

その他の回答 (3 件)

Alexandre Laurin
Alexandre Laurin 2013 年 2 月 23 日
編集済み: Alexandre Laurin 2013 年 2 月 23 日
assignin('caller',['h_ann_' num2str(k)], dummy)
will work unless you are calling this function from another function (or script), in which case the problem is a little deeper.
Also, you might want to have a look at structures with dynamic field names, I'm pretty sure they'll do what you want to do with more elegance.

Jan
Jan 2014 年 1 月 11 日
Hiding an index in the name of a variable is a bad idea. It is complicated, as you see already, and requires equivalently complicated method to access these variables later on.
Better use an index as index:
h_ann = cell(1, 6);
for k=1:6
...
h_ann{k} = dummy;
end

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 4 日
編集済み: Azzi Abdelmalek 2013 年 2 月 4 日
dummy=20
k=3;
assignin('base',sprintf('h_ann%d',k),dummy)
  1 件のコメント
Muge Erinc
Muge Erinc 2013 年 2 月 4 日
Thanks for your answer. however i intentionally do not want to use the base, i want to write it into the functions local workspace.

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

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by