Need help with a While loop
Show older comments
So I'm trying to write a rainflow counting program and I'm having trouble with the repetitions
while i <= numel(PV) ;
i = i +1;
N = N+ 1;
PV(N);
switch N
case 3
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
case 4
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
end
end
Instead of doing cases all the way to 24 there must be an easier way but I suck at matlab and would appreciate any help. Thanks
1 Comment
Nicolo Zaza
on 19 Jul 2012
Accepted Answer
More Answers (4)
Walter Roberson
on 19 Jul 2012
Why have a switch at all? Why not just
if N >= 3
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
end
2 Comments
Andrei Bobrov
on 19 Jul 2012
if N >= 3 && N <= 4
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
end
Albert Yam
on 19 Jul 2012
Following from Nicolo's response about keeping X,Y values.
for N = 3:length(PV)
if N >= 3 && N <= 4
X(N-2) = abs(PV(N) - PV(N-1))
Y(N-2) = abs(PV(N-1) - PV(N-2))
end
end
but at this point.. Walter is right .. why loop?
X = PV(3:end);
Y = PV(3:end);
X(1) = abs(PV(3) - PV(2));
X(2) = abs(PV(2) - PV(1));
Y(1) = abs(PV(3) - PV(2));
Y(2) = abs(PV(2) - PV(1));
Matt Kindig
on 19 Jul 2012
Edited: Matt Kindig
on 19 Jul 2012
I reformatted the code for easier reading. A few questions:
- 1. what are X and Y for? They don't appear to be used anywhere in the loop, and are overwritten each time.
- 2. For N=3 or N=4, X and Y are defined in the same way.
- 3. Are i and N initialized prior to the loop?
- 4. What exactly is this code supposed to do? If we understand your intended output more clearly, we can probably recommend a more direct approach.
Your code:
while i <= numel(PV)
i = i +1;
N = N+ 1;
PV(N);
switch N
case 3
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
case 4
X = abs(PV(N) - PV(N-1))
Y = abs(PV(N-1) - PV(N-2))
end
end
1 Comment
Nicolo Zaza
on 19 Jul 2012
Edited: Jan
on 19 Jul 2012
Andrei Bobrov
on 19 Jul 2012
Edited: Andrei Bobrov
on 19 Jul 2012
switch N
case {3,4}
X = abs(PV(N) - PV(N-1));
Y = abs(PV(N-1) - PV(N-2));
end
OR
k = abs(diff(PV(1:4)));
xy = flipud(k(hankel(1:2,2:3)))
X = xy(1,N-2);
Y = xy(2,N-2);
Nicolo Zaza
on 19 Jul 2012
0 votes
1 Comment
Albert Yam
on 19 Jul 2012
The reason you only get 1 set of X, Y, is because you tell Matlab to over write it. This is the first instance of you mentioning that you need to keep previous X, Y values.
for N=1:length(PV)
if N<3
%stuff
end
end
Categories
Find more on Fluid Dynamics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!