Fast method to store workspace variables into another worspace variable?
1 次查看(过去 30 天)
显示 更早的评论
Hi- i would like a fast method to store all workspace variables into another workspace variable.
My current slow method is this...
tmp=tempname;
save(tmp)
x = load(tmp);
delete(tmp)
any better ideas?
1 个评论
Walter Roberson
2011-11-16
I think you will find that that method does not work when it comes to objects, and I think you will find it doubles the memory instead of sharing it (until the next write to the variables anyhow.)
回答(1 个)
Sean de Wolski
2011-11-16
You could pass them into the function the typical way
function y = some_fun(tmp,x)
y = x*tmp;
Or you can use setappdata/getappdata, though this can be dangerous. It is very fast though. To do it, I recommend packing everything into a struct or a cell and saving it as some obscure name. I have had to do this for big variables passed between functions that are called (literally) billions of times.
S.tmp = tmp;
S.x = x;
setappdata(0,'S_2be_used_in_foobar',S);
%in foobar
function y = foobar()
S = getappdata(0,'S_2be_used_in_foobar'); %pull in
tmp = S.tmp; %extract
x = S.x
y = tmp*x;
Just note this can be very dangerous and is generally recommended against. To safeguard it, use a long name with lots of underscores and numbers.
3 个评论
Sean de Wolski
2011-11-21
If you're still wondering. Storing data to the root directory is dangerous since that's where MATLAB stores some important things that if overwritten or reset could cause fatal/difficult to trace errors.
Sean de Wolski
2011-11-21
And yes, you could do a loop, I would recommend using the loop to pack everything into a struct using the fieldnames option.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!