user1892115
user1892115

Reputation: 87

Traverse matrix in segments

I have a huge waveform matrix:

[w,fs] = wavread('file.wav');
length(w)
ans =

  258048

I want to go through this matrix in segments (say 50) and get the maximum of these segments to compare it to another value. I tried this:

thold = max(w) * .04;
nwindows = 50;
left = 1;
right = length(w)/nwindows;
counter = 0;
for i = 1:nwindows
  temp = w(left:right);
  if (max(temp) > thold)
      counter = counter + 1;
  end
  left = right;
  right = right+right;
end

But MATLAB threw tons of warnings and gave me this error:

Index exceeds matrix dimensions.

Error in wlengthdur (line 17)
  temp = w(left:right);

Am I close or way off course?

Upvotes: 1

Views: 288

Answers (1)

Dan
Dan

Reputation: 45752

An alternative approach would be to use reshaped to arrange you vector in to a 2D matrix with number of row n and columns equal to ceil(length(w) / n) i.e. round up so that it is divisible as matlab matrices must be rectangular. This way you can find the max or whatever you need in one step without looping.

w = randn(47, 1);
%this needs to be a column vector, if yours isn't call w = w(:) to ensure that it is

n = 5;

%Pad w so that it's length is divisible by n
padded = [w; nan(n - mod(length(w), n), 1)];

segmented_w = reshape(padded, n, []);

max(segmented_w)

Upvotes: 1

Related Questions