0

I have a question regarding indexing and loops in MATLAB. I have a vector of length n (named data in the code below). I want to examine this vector 4 elements at a time inside of a for loop. How can I do this? My attempt included below does not work because it will exceed the array dimensions at the end of the loop.

for k = 1:length(data)

    index = k:k+3;

    cur_data = data(index);

    pre_q_data1 = cur_data(1);
    pre_q_data2 = cur_data(2);
    % Interweaving the data
    q = [pre_q_data1; pre_q_data2];
    qdata = q(:)';


    pre_i_data1 = cur_data(3);
    pre_i_data2 = cur_data(4);

    i = [pre_i_data1; pre_i_data2];
    idata = i(:)';

end    
3
  • You need to stop when k+3 is equal to the last index of the array, not when it's equal to end+3. Commented May 17, 2017 at 15:00
  • Also you can get rid of the for-loop and use buffer instead. See here. Commented May 17, 2017 at 15:48
  • @kedarps, * "Also you can [...] use buffer instead if you have the signal processing toolbox" Commented May 17, 2017 at 15:54

1 Answer 1

0

You shouldn't have k go all the way to length(data) if you're planning on indexing up to k+3.

I've also taken the liberty of greatly simplifying your code, but feel free to ignore that!

for k = 1:length(data)-3
    % maximum k = length(data)-3, so maximum index = length(data)-3+3=length(data)
    index = k:k+3;
    cur_data = data(k:k+3);
    % Interweaving the data
    q = cur_data(1:2); % transpose at end of line here if need be
    i = cur_data(3:4); % could just use data(k+2:k+3) and not use cur_data
end   
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot... Sometimes the simplest solutions fly right over your head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.