How do i get matlab to break from a nested loop but then go back into the loop?

4 views (last 30 days)
So ill try to be as clear as i can
Im basically trying to do a double summation here.
The problem is there are two variables that must advance at the same time.
When i use break it kicks me out of my inner loop goes outside, continues the outer one but never gets back to the inner one?
What do i do?
count = 0
sum = 0
for N = [-5,-4,-3,-2,-1,0,1,2,3]
for X = [3,1,-5,-11,0,-5,3,3,8]
sum = sum + X*exp(-j*pi*N)
%count was used just for debugging to see things line by line
count = count + 1
break
end
end
disp(sum);
So as you can see from my code for the first run through N = -5 It should go to the next loop where X = 3 and make a calculation. then it should break out of that loop and return to the top. Index N up so it now = -4 and then go back to my inner for loop where X should = 1 and continue calculation.
However whoever i try to use break it never goes back to the inner loop and just keeps advancing the outer loop without doing anything.
Also can someone tell me how to set up matlab to debug line by line like a C code

Accepted Answer

Walter Roberson
Walter Roberson on 22 Feb 2016
Nvals = [-5,-4,-3,-2,-1,0,1,2,3];
XVals = [3,1,-5,-11,0,-5,3,3,8];
total = 0;
for idx = 1 : length(Nvals)
N = Nvals(idx)
X = Xvals(idx)
total = total + X*exp(-j*pi*N)
end
Or more simply
N = [-5,-4,-3,-2,-1,0,1,2,3];
X = [3,1,-5,-11,0,-5,3,3,8];
total = sum(X .* exp(-j*pi*N));
  3 Comments
Robert
Robert on 22 Feb 2016
I tried your second version but it keeps giving me an error about subscript indices? any ideas?
Robert
Robert on 22 Feb 2016
I got your first version working, there was just a small typo that was giving me an error.
Thank you so much for your help. I will put that trick in the back of my brain for next time

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!