Effacer les filtres
Effacer les filtres

Since my variable changes size on every loop iteration, how do I preallocate memory?

2 vues (au cours des 30 derniers jours)
MATLAB says that my variable activity_dff changes size on every loop iteration and for this reason I should consider preallocating. I do know the size of the array before the for loop begins (I do know it'll always have 1 row and n columns, where n is equal to the number of rows of another variable Activity_smooth), so I should probably preallocate it and then shrink it afterwards by doing: X = X(1:n,:);
%% Calculate dff
fd = prctile(Activity_smooth,10); %baseline, f0
% Calculating Activity(k)-fd/fd for photometry
for k = 1:length(Activity_smooth)
Activity_dff(k) = (Activity_smooth(k)-fd)/fd;
end
Activity_dff_ds = group_z_project_vector(Activity_dff,2560); %to see in epoch
end
Is the following code correct? And how do I make sure it's faster than the previous one?
%% Calculate dff
fd = prctile(Activity_smooth,10); %baseline, f0
% Calculating Activity(k)-fd/fd for photometry
Activity_dff = zeros(1,1000000);
for k = 1:length(Activity_smooth)
Activity_dff(k) = (Activity_smooth(k)-fd)/fd;
end
Activity_dff = Activity_dff(:,1:length(Activity_smooth));
Activity_dff_ds = group_z_project_vector(Activity_dff,2560); %to see in epoch
end

Réponse acceptée

Image Analyst
Image Analyst le 5 Avr 2020
You can do this:
%% Calculate dff
fd = prctile(Activity_smooth,10); %baseline, f0
% Calculating Activity(k)-fd/fd for photometry
Activity_dff = zeros(1, length(Activity_smooth));
for k = 1:length(Activity_smooth)
Activity_dff(k) = (Activity_smooth(k)-fd)/fd;
end
Activity_dff = Activity_dff(1:length(Activity_smooth));
Activity_dff_ds = group_z_project_vector(Activity_dff,2560); %to see in epoch
or even better, get rid of the loop and other unneeded stuff:
%% Calculate dff
fd = prctile(Activity_smooth,10); %baseline, f0
Activity_dff = Activity_smooth-fd ./ fd;
Activity_dff_ds = group_z_project_vector(Activity_dff,2560); %to see in epoch

Plus de réponses (1)

Ameer Hamza
Ameer Hamza le 5 Avr 2020
Modifié(e) : Ameer Hamza le 5 Avr 2020
From you code, it appear that Activity_dff is of same size as Activity_smooth
% Calculating Activity(k)-fd/fd for photometry
Activity_dff = zeros(size(Activity_smooth)); % <---- pre-allocation
for k = 1:length(Activity_smooth)
Activity_dff(k) = (Activity_smooth(k)-fd)/fd;
end
Activity_dff_ds = group_z_project_vector(Activity_dff,2560); %to see in epoch

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by