# Splitting a signal in MATLAB

Discussion in 'Programmer's Corner' started by battlehands, Aug 17, 2011.

1. ### battlehands Thread Starter New Member

Jul 29, 2011
13
0
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?

2. ### steveb Senior Member

Jul 3, 2008
2,433
469
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.

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

Code ( (Unknown Language)):
1. subsig1=subsig(1,:)
2. subsig2=subsig(2,:)
3. subsig3=subsig(3,:)
4. subsig4=subsig(4,:)
5. 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: Aug 18, 2011
battlehands likes this.
3. ### Mohamed Elforjani New Member

Nov 10, 2012
4
0
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

4. ### Mohamed Elforjani New Member

Nov 10, 2012
4
0
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