Vectorizing nested for loop
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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));
0 Kommentare
Antworten (1)
Sulaymon Eshkabilov
am 10 Jun. 2021
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().
0 Kommentare
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!