Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

crazy loop 1

Status
Not open for further replies.

Star1976

Materials
Jan 31, 2005
6
Hi Guys
Have a look at the following simple matlab code:

x=[1;2;3;4;5;6;7;8;9;10];
y=[5;4;3;6;7;8;5;4;3;2];
z=[1;2;-7;-4;5;-1;4;-9;-6;5]

x1 = zeros(m, 1);% initialise output matrix
y1 = zeros(m, 1);
z1 = zeros(m, 1);

for i = 1:m;
x1(i) = x(i);
y1(i) = y(i);
z1(i) = z(i);

if z1(i)<0 % to choose the negative elements
if z1(i+1)>0 % if the next element is positiv
plot(x(i),y(i),'o')
hold on
end
end
end
------------------

I want to plot x versus y when z sign change from negative to positive ( z passes through zero). Matlab does not consider the second loop where I try to examine the following element. The answer is probably easy and silly but I spent few days without any success.

Any idea or suggestion??

Help is greatly appreciated.

Regards

Star
 
Replies continue below

Recommended for you

Sorry I forgot to define m, the code should be:

x=[1;2;3;4;5;6;7;8;9;10];
y=[5;4;3;6;7;8;5;4;3;2];
z=[1;2;-7;-4;5;-1;4;-9;-6;5]

m = size(x, 1);

x1 = zeros(m, 1);% initialise output matrix
y1 = zeros(m, 1);
z1 = zeros(m, 1);

for i = 1:m;
x1(i) = x(i);
y1(i) = y(i);
z1(i) = z(i);

if z1(i)<0 % to choose the negative elements
if z1(i+1)>0 % if the next element is positiv
plot(x(i),y(i),'o')
hold on
end
end
end
 
Your problem is
Code:
if z1(i+1)>0
Your looking one sample ahead of the computation and according to
Code:
z1 = zeros(m,1)
this sample is always zero.

Something like this should solve the problem.
Code:
for i = 2:m
   if (z1(i-1)<0 & z1(i)>0)
      plot(....)
   end
end
 
Thanks Jockek.

That really works nicely.

Well done!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor