How to do this without a loop

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 个评论

When you ask a question , make sure that the third person is able to run your code first! There are some missing datas.

请先登录,再进行评论。

回答(1 个)

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 个评论

Time(:, 2:end) = Time(:, 1:end-1) + (1:size(Time,2) - 1) / (Fs*1000);
Thank you for your answer.
The error was not about the code but running time. It takes very long and my pc is not capable to handle it. Therefore writing a code without a loop solves my problem.
When I run your line, calculated values are not correct. It gives the same values for every column accept 2nd. I want to have : n = (n-1) + 1/(Fsx1000). I attached the resulted matrix.
@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?

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 MATLAB Mobile 的更多信息

提问:

2019-1-7

编辑:

Jan
2019-1-8

Community Treasure Hunt

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

Start Hunting!

Translated by