Vectorizing nested for loop

15 次查看(过去 30 天)
Shai
Shai 2021-6-10
I am struggling to accurately vectorize this nested loop. Right now, the loop takes 2-8 hours to run, so I would like to reduce that time if possible. Help appreciated.
%% Parameters
m=3; %AR model order
lambda=225;%lambda=10 for smoothing priors
nfft=656 ; %(nearest even number of volume)
fs=0.7143;%1/TR
%add leading 0 for subject names
subject = sprintf('%06d',subject);
%files
ASCII_File = fullfile(['path/',num2str(subject),'/path/',num2str(subject),'_task-rest_acq-AP_run-01_bold_']);
outdir = fullfile(['path/',num2str(subject),'/path/']);
%% preallocate
totalData = zeros(5632,88,657);
power = zeros(329,88);
%% subject
tStart = tic;
disp(["Begining MATLAB Processing of subject: ", num2str(subject)])
for v = 0:656
n=v+1;
vname=num2str(v.','%05d');
BOLDdatafile = [ASCII_File,vname];
Ascii = importdata(BOLDdatafile);
totalData(:,:,n)=Ascii(:,:);
end
disp('Starting XYZ transformations')
for z=1:64 % z dimension
X = ['z: ',num2str(z)];
disp(X)
power=[];
volume=[];
for y=1:88 % y dimension
X = ['y: ',num2str(y)];
disp(X)
row= y+(88*(z-1)); %actual row number in ascii file
disp(row)
volume(:,:) = totalData(row,:,:);
for x=1:88 % x dimension
X = ['x: ',num2str(x)];
rawy = volume(x,:).';
%('1. SMOOTHING PRIORS')
T=length(rawy);
I=speye(T);
D2=spdiags(ones(T-2,1)*[1 -2 1],[0:2],T-2, T);
z_stat=(I-inv(I+lambda^2*D2'*D2))*rawy;
SPy=z_stat;
[pxx,f] = pburg(SPy,m,nfft,fs);
power(:,x)=pxx;
end
for n=0:328
oname=num2str(n.','RS_%05d');
outfile=[outdir,oname];
vol=n+1;
if z==1
dlmwrite(outfile,power(vol,:),'-append','delimiter',' ');
else
if y==1
dlmwrite(outfile,power(vol,:),'-append','delimiter',' ','roffset',1);
else
dlmwrite(outfile,power(vol,:),'-append','delimiter',' ');
end
end
end
end
end
tEnd = toc(tStart);
fprintf('FINSHED! Time to completion: %d minutes and %.2f seconds\n', floor(tEnd/60), rem(tEnd,60));

回答(1 个)

Sulaymon Eshkabilov
Most of your simulation time because of the data import from other data file sources importdata() and exporting the data to external data file via dlmwrite().
It does not seem to be possible to vectorize these data import and export as shown in your code.
Note that importdata() is slow. If feasible, substitute it with some other data import fcns, such as textscan(), fscanf().

类别

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

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by