Element-by element wise matrix addition of pieces of a matrix

Hi, I apologize if this question is very simple, I am new to MATLAB! I need to take a vector that is 1024 elements, and sum the first 256 elements , ie 1+257, 2+258, etc. I keep getting an error that matrix dimensions don't agree, but I don't understand since I am adding 256 elements each time. I need the vector xx2cyc to be (256,1) when it is done.
Here is my code:
Navg = 10;
jj = 1;
jjj = 256;
overLapPercent = 0.5;
Overlap = 1024 * overLapPercent;
k = 1;
xx2cyc = zeros(256,1);
for ii = 1:Navg
%Overlap processing
ff = y1(k:k+1024-1);
xx2 = y2(k:k+1024-1);
ff = hann(1024).*ff'; %Window data
xx2 = hann(1024).*xx2';
%Cyclic Averaging, for 4 cyclic averages
xx2cyc = xx2(jj:jjj) + xx2(jjj:2*jjj); + xx2(2*jjj:3*jjj) + xx2(3*jjj:4*jjj);
xx2cyc= xx2cyc./4;
k=k+Overlap;
end

 Accepted Answer

Your code would be much easier to understand, and self-documented, if you used meaningful variable names, as you did for Overlap. I kept having to refer back to the declaration in order to remember what k, ff, xx2, jj, jjj (seriously, you just keep adding 'j' to the names?) were.
Anyway, the error is a typical off by one error, jj:jjjj == 1:256 is 256 elements, jjj:2*jjj == 256:512 is 257 elements. It should have been jjj+1:2*jjj.
However, a better way of doing this is simply reshaping the vector into four rows of 256 columns and summing these rows. It's much clearer, and you're guaranteed not to make offset errors:
xx2cyc = mean(reshape(xx2(1:1024), 4, [])); %sum(xxx)./4 is mean.

2 Comments

Thanks, this worked. I only use names like this for dummy counter variables. xx2 makes sense in the context of what I'm doing (time domain response, 2nd channel) ff, force input, time domain indicated by lowercase.
Whatever the context, xx2 has no meaning. tdresponse does. Similarly, forceinput is immediately more obvious, self-documenting, than ff.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!