How to do this without a loop
Afficher commentaires plus anciens
I have an time vector and want to assign values for the column (2:end). Following is my code which is working, however, due to for loop on a large data it is very slow and after a while it crashed an 'out of memory' error poped up. I am a beginner Matlab user. So I would be very happy to get any suggestion to shorten my code and run faster without a crash?
Time(:,1:3)=date(:,1:3); % taking date from date vector - yyyy mm dd
Time(:,4:7)=timevec(:,1:4); % taking time from time vector - HH:MM:SS:MS
Time(:,6)=round(((Time(:,7)/1000)+Time(:,6)),2); % Convert millisecond into second and add second column
Time(:,7)=[]; % Empty millisecond column
Time=datenum(Time); % convert date and time into serial number
Time=Time*24*60*60*1000; % convert serial number into millisecond
Time=Time-Time(1);
Fs=96000; % Sampling Frequency Hz
[m,n]=size(data); % data matrix = 2074x4800
Time(m,n)=0; % Extend time matrix to the same size as data matrix
%% Assign time to the extended part of time matrix
for j=2:size(Time,2)
Time(:,j)= Time(:,(j-1))+(1/(Fs*1000));
end
1 commentaire
madhan ravi
le 7 Jan 2019
When you ask a question , make sure that the third person is able to run your code first! There are some missing datas.
Réponses (1)
Jan
le 7 Jan 2019
The code is not useful currently. What is the purpose of:
Time(:,1)=Time(:,1)
? It does nothing but polluting the command window.
for j = 2:size(Time,2)
Time(:,j)= Time(:,(j-1))+(1/(Fs*1000));
end
This does not change the size of the array Time, therefore you cannot get a memory problem here. Please post the complete error message, which would tell us, where the problem occurs.
By the way: You do not need a loop for this calculation:
Time(:, 2:end) = Time(:, 1:end-1) + (1:size(time,2) - 1) / (Fs*1000);
2 commentaires
NoMo
le 8 Jan 2019
@NoMo: You have written "after a while it crashed an 'out of memory' error" - this does not sound like a runtime problem.
Maybe you want:
Time(:, 2:end) = Time(:, 1) + (1:size(Time,2) - 1) / (Fs*1000)
I cannot confirm, that my former suggestion:
Time(:, 2:end) = Time(:, 1:end-1) + (1:size(Time,2) - 1) / (Fs*1000)
"gives the same values for every column". Perhaps you did not copy my code exactly?
Catégories
En savoir plus sur MATLAB Mobile dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!