if-else within for loop

11 views (last 30 days)
Shaban Akhtar
Shaban Akhtar on 16 Mar 2019
Commented: Shaban Akhtar on 16 Mar 2019
clc
clear all
k=4;
a=13;
for i=1:10
c(i)=i*k;
b(i)=a+c(i);
end
for i=1:10
if 26<b<39
e=b+k;
else e=b/k;
end
end
disp(e)
disp(c)
disp(b)
  1 Comment
Shaban Akhtar
Shaban Akhtar on 16 Mar 2019
expression under IF works but else does not.

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 16 Mar 2019
% Vectorized version (efficient than a loop)
k=4;
a=13;
ii=1:10
c=ii*k;
b=a+c;
e=b/k;
e(b>=26 & b<59)=b(b>=26 & b<59)+k
disp(e)
disp(c)
disp(b)
% Loop version
k=4;
a=13;
c=zeros(1,10); % pre-allocate
b=c;
for ii=1:10
c(ii)=ii*k;
b(ii)=a+c(ii);
if (b(ii)>=26 && b(ii)<59) % proper usage
e(ii)=b(ii)+k;
else
e(ii)=b(ii)/k;
end
end
disp(e)
disp(c)
disp(b)

More Answers (0)

Categories

Find more on Programming 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!