How to avoid repeating load data from a function
6 ビュー (過去 30 日間)
古いコメントを表示
dear all,
I have a function that will be call 1000 times. In that function, there are several "load" sentence to load some data. And I have another function to call this function 1000times. The data will be loaded 1000 times. If I put the load to the outside function, actually the data will not go into the inside function. How can I just load once and loop the function 1000 times?
0 件のコメント
回答 (1 件)
Walter Roberson
2012 年 2 月 11 日
Shared variables with a nested routine; or pass the values in to the routine.
Note that shared variables must be initialized (to any value) before the nested routine is declared.
function ndemo
foo = []; %okay to share
bar = []; %okay to share
function nested
biz = foo + bar; %okay, references previously-declared vars
baz = biff; %not okay, this will not exist until run time
end
biff = []; %not okay to share with "nested"
load fingle.mat; %load values for foo and bar and biff
[foo, bar, biff] %will show the loaded values
nested(); %will error saying biff was unknown
end
To emphasize: it isn't enough for the value of a variable to be known at execution time in order for it to be shared with a nested function: the variable has to have been given some visible value before the nested routine was declared, not before it was executed.
2 件のコメント
Walter Roberson
2012 年 2 月 13 日
Then I suggest using "persistent".
persistent characters
persistent space_variance
and so on. Then have a test such as
if isempty(characters)
load characters.mat;
load cluster_record2.mat;
load space_variance.mat;
%etc
end
This will only do the load if the data has not already been loaded.
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!