writing a conditional for loop

3 views (last 30 days)
Melissa
Melissa on 9 Jan 2015
Commented: Melissa on 9 Jan 2015
Good Morning,
I am having a little trouble with my for loop and was hoping someone would be so kind to assist me. Given a set of data (x and y) I am trying to add or subtract some type of factor (SF) depending on the value of y (if y is negative add SF, if y is positive subtract SF). Currently, the for loop works only one transition (y value negative to positive or positive to negative) and not for more than one (positive to negative back to positive). Can anyone help or advise me how to fix my for loop to meet this requirement?
Thanks so much,
x=[808.284900000000
809.904900000000
811.672700000000
813.550100000000
815.487700000000
817.448500000000
819.423900000000
821.410000000000
823.402300000000
825.398000000000
827.395300000000
829.393300000000
831.391000000000
833.387900000000
835.383400000000
837.377400000000
839.369600000000
841.360100000000
843.349500000000
845.338100000000
847.327900000000
849.319400000000
851.308000000000
853.282900000000
855.228400000000
857.128500000000
858.966900000000
860.726800000000
862.391200000000
863.942900000000
865.363700000000
866.635600000000
867.755100000000
868.739100000000]
y=[-0.816189993942800
-0.622532051258187
-0.465001282100469
-0.348391977260414
-0.261473638062749
-0.191273590942197
-0.132866762880952
-0.0881180486304432
-0.0533090231370573
-0.0252337776469318
-0.00206907369705616
0.0184769297699437
0.0347815426828506
0.0481862132226801
0.0595367304830828
0.0656045719796771
0.0694017195361085
0.0756086524233473
0.0834593432210734
0.0943319089332969
0.110783369645501
0.133136452858768
0.164766476287160
0.213511396624337
0.283854001540591
0.377411457727238
0.485875804686940
0.608688085270419
0.752808499297550
0.916389742694352
1.10881324759990
1.34895494996045
1.62877923091320
1.92595565865132];
d1=1.96707649837704;
SF=d1/length(x);
for i=1:length(y)
SF=d1/length(x);
if y(i) < 0
y(i)=y(i)+SF;
elseif y(i) > 0
y(i)=y(i)-SF;
end
end

Accepted Answer

Alessandro
Alessandro on 9 Jan 2015
Edited: Alessandro on 9 Jan 2015
neg = find(y<0);
pos = find(y>0);
y(neg) = y(neg)+SF;
y(pos) = y(pos)-SF;
  2 Comments
Melissa
Melissa on 9 Jan 2015
Thanks so much for your quick response. I looked this up, I think its called logical indexing, and tried using the code provide (greatly appreciated) but still when applying it doesnt include a tranisition back from positive to negative.
Melissa
Melissa on 9 Jan 2015
Wait, I mixed in the old code with that one. It worked out perfectly! Thank you!!!!!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!