adding constraints with if loop

a1=1:.3:5.2;
b1=3:.2:5.8;
c1=2:.3:6.2;
for k=1:15
composite=[a1(:,k) b1(:,k) c1(:,k)];
origin=[1.3 1.1 1.5];
d(:,k)=sqrt(sum((composite-origin).^2));% 1*15 vector
end
But now in 'composite' I want to exclude those all points which have a1 less than or equal to 1.5, b1 greater than or equal to 5 and c1 less than or equal to 2. So now my d vector will be 1*6 instead of 1*15. How can I get this result with combination of for and if loop.

3 Comments

There is no such thing as an "if loop"
You are right. I mean 'if conditional'. Thanks!
'S'ok. I'm just trying to prevent the phrase from spreading as several people started using it.

Sign in to comment.

 Accepted Answer

And if it must be done with "for" and "if" then,
a1=1:.3:5.2;
b1=3:.2:5.8;
c1=2:.3:6.2;
origin=[1.3 1.1 1.5];
numv = 0;
d = [];
for k=1:15
composite=[a1(:,k) b1(:,k) c1(:,k)];
if composite(1) <= 1.5 || composite(2) >= 5 || composite(3) <= 2;
continue;
end
numv = numv + 1;
d(:,numv)=sqrt(sum((composite-origin).^2));
end

2 Comments

You used if+continue+end. I guessed that your code continue the calculation of d when if statements do not hold good and ends calculation of d when if conditions are true. Am I right? How can I do it other way, e.g. find d only when a1 is greater than 1.5, less than 5; b1 less than or equal to 5;c1 greater than or equal to 2 and less than 5.8. Otherwise when these if statements do not apply end my calculation.
can it also be done with while+break and for+break. Thanks!
if composite(1) >= 1.5 & composite(1) < 5 & composite(2) <= 5 & composite(3) >= 2 & composite(3) < 5.8
numv = numv + 1;
d(:,numv)=sqrt(sum((composite-origin).^2));
end
This is a different way of writing the same control: select what you do want rather than rejecting what you do not want.
When you say "end my calculation", if you mean for the entire loop over "k", then before just before the "end" of the "if", add
else
break
But take note that this will result in no work being done, as a1(1) is out of the desired range. So probably you just want to do what I have written here, do not calculate the result if the values are out of range for this k.

Sign in to comment.

More Answers (1)

a1=1:.3:5.2;
b1=3:.2:5.8;
c1=2:.3:6.2;
composite=[a1(:), b1(:) c1(:)];
Lidx_a = a1 <= 1.5;
Lidx_b = b1 >= 5;
Lidx_c = c1 <= 2;
composite((Lidx_a | Lidx_b | Lidx_c),:) = [];
nrow = size(compisite,1);
origin=[1.3 1.1 1.5];
d = sqrt( sum( (composite-repmat(origin,nrow,1)).^2, 2) );
No loop needed.
The second argument to sum, the 2, is needed to sum along rows.

Categories

Find more on Loops and Conditional Statements 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!