Does loading a table in a subfunction I'm calling slow my routine down?

1 次查看(过去 30 天)
I have a script which contains a function that calls a sub-function many times, where the sub-function analyzes data from a large, read-only 8000 x 5 table that never changes. I load the table at the beginning of the sub-function. Question: am I slowing down my script dramatically by re-loading the same data each time I call the sub function? Is there a better way to do this? Simplified code below:
**********myfun.m********************
function tt = myfun(z)
i = 1;
sum_one = 0;
sum_two = 0;
for i = 1:z;
t = mysubfun(i);
sum_one = sum_one + t(1,1)
sum_two = sum_two + t(1,2)
end
tt = table(sum_one, sum_two)
end
***********mysubfun.m*******************
function t = mysubfun(x)
load('data.mat') %loads a table that is 8000 x 5
t = table(sum(data(1:x,1),sum(data(1:x,2))
end

采纳的回答

Matt J
Matt J 2018-1-11
编辑:Matt J 2018-1-11
Yes, you are dramatically slowing things down.
I can't be sure what your code is trying to do (it would produce error messages as you've written it), but I don't think you need the sub-function or even the loop. I think it can all be done in two lines as follows,
load('data.mat')
tt=array2table( cumsum(data(:,1:2),1) );
  6 个评论
Matt J
Matt J 2018-1-11
编辑:Matt J 2018-1-11
That really is not a good idea, for one thing because global variables cannot be made read-only. You should probably just pass data around as a regular function input argument as below.
function tt = myfun(z)
S=load('data.mat') %loads a table that is 8000 x 5
data=S.data; clear S
i = 1;
sum_one = 0;
sum_two = 0;
for i = 1:z;
t = mysubfun(i,data);
sum_one = sum_one + t(1,1);
sum_two = sum_two + t(1,2);
end
tt = table(sum_one, sum_two);
end
function out = mysubfun(x,data)
out = table( sum(data(1:x,1)) , sum(data(1:x,2)) );
end
However, if for some reason this is too cumbersome, the next best thing would be to make the data a Constant property of a class
classdef readOnly %put in a file called readOnly.m
properties (Constant)
data=getfield(load('data.mat'), 'data');
end
end
Now, any function anywhere can access the data, like in the following
function tt = myfun(z)
i = 1;
sum_one = 0;
sum_two = 0;
for i = 1:z;
t = mysubfun(i);
sum_one = sum_one + t(1,1);
sum_two = sum_two + t(1,2);
end
tt = table(sum_one, sum_two);
end
function out = mysubfun(x)
out = table( sum(readOnly.data(1:x,1)) ,...
sum(readOnly.data(1:x,2)) );
end
qmnjb007
qmnjb007 2018-1-11
Thanks Matt and Steven; loading the data in the main script and then passing the structure to the functions was the solution I was looking for!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by