if-else within for loop

조회 수: 11 (최근 30일)
Shaban Akhtar
Shaban Akhtar 2019년 3월 16일
댓글: Shaban Akhtar 2019년 3월 16일
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
Shaban Akhtar
Shaban Akhtar 2019년 3월 16일
expression under IF works but else does not.

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 3월 16일
% 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)
  댓글 수: 1
Shaban Akhtar
Shaban Akhtar 2019년 3월 16일
Thank u so much sir

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by