Splitting a signal in MATLAB

Thread Starter

battlehands

Joined Jul 29, 2011
13
I have a signal that is 40 seconds long. I need to split it into 5 equal sections of 8 seconds.

I could do this the long way by:

let my signal = sig
then

subsig1 = sig(1:8*Fs)
subsig2 = sig((8*Fs)+1:16*Fs)
subsig3 = sig((16*Fs)+1:24*Fs)
subsig4 = sig((24*Fs)+1:32*Fs)
subsig5 = sig((32*Fs)+1:40*Fs)

However, I want to do this in a loop. Can anyone help?
 

steveb

Joined Jul 3, 2008
2,436
I have a signal that is 40 seconds long. I need to split it into 5 equal sections of 8 seconds.

I could do this the long way by:

let my signal = sig
then

subsig1 = sig(1:8*Fs)
subsig2 = sig((8*Fs)+1:16*Fs)
subsig3 = sig((16*Fs)+1:24*Fs)
subsig4 = sig((24*Fs)+1:32*Fs)
subsig5 = sig((32*Fs)+1:40*Fs)

However, I want to do this in a loop. Can anyone help?
There is nothing wrong with what you did, but if you want to do it in a loop, you could put the signal into a 2D array, rather than separate 1D vectors.

Rich (BB code):
for k=1:5
 subsig(k,:)=sig( 1+(k-1)*8*Fs : k*8*Fs )
end
Then if you need separate variables you can do what you did in a straightforward way.

Rich (BB code):
subsig1=subsig(1,:)
subsig2=subsig(2,:)
subsig3=subsig(3,:)
subsig4=subsig(4,:)
subsig5=subsig(5,:)

There may be other ways to do it. In the old days, using FORTRAN, we could do this with no work at all by using a COMMON block and associating two variable array names to the same data. One array was declared as a 2D array and the other as a 1D array. The variables names basically shared the same locations in memory so that if you changed the contents of the memory using one variable name, it automatically was changed for the other variable name. I don't know that you can do this in Matlab, but it might be worth checking. Otherwise it's just a matter of pointing to the correct locations, but do it in a way that is efficient in Matlab. Running nested loops and grabbing individual values is very slow in Matlab. It's best to use vector operations as you did originally.
 
Last edited:
clear all;
clc;
close all;
% assume the following data
Fs = 100;
sig = 1:40;
count = 0;

for k = 1:8:length(sig);
count = count + 1;
sub_sig = sig(k:k+8-1).*Fs;
fprintf('\n')
fprintf('Set Number %1.0f \n',count);
fprintf('============\n')
fprintf('%4.0i\n',sub_sig);
end
 
Sorry I just joined the forum

try this code

clear all;
clc;
close all;
% assume the following data
Fs = 100;
sig = 1:40;
count = 0;

for k = 1:8:length(sig);
count = count + 1;
sub_sig = sig(k:k+8-1).*Fs;
fprintf('\n')
fprintf('Set Number %1.0f \n',count);
fprintf('============\n')
fprintf('%4.0i\n',sub_sig);
end
 
Top