필터 지우기
필터 지우기

If Loop for specific condition

조회 수: 6 (최근 30일)
Fereizqo Sulaiman
Fereizqo Sulaiman 2018년 2월 27일
답변: Esha Almas 2020년 3월 4일
Hello, i've written the following script in MATLAB:
i = 1:0.5:50;
for t = [-5:0.5:50]
if t<10
v = 11.*t.^2 - 5.*t;
elseif t<20.5 && t>10
v = 1100-5.*t;
elseif t<30.5 && t>20
v = 50.*t + 2.*(t-20).^2;
elseif t>30
v = 1520.*exp(-0.2.*(t-30));
else
v = 0;
end
end
fprintf('value of v: %d\n', v);
I want to get value of v in every t condition First condition, t < 10 Second condition, 10<t<20 Third condition, 20<t<30 Forth condition, t>30 and if none of them, the value of v is 0 Thanks for your help

채택된 답변

KL
KL 2018년 2월 27일
is it a homework? should you really use for loop and if-else statements?
I suppose yes. In that case, you need to store your calculated v after every iteraton. For example,
t = -5:0.5:50; %here you define t
and you may want to store v for every t, so pre-allocate v for the same size now,
v = zeros(size(t));
now, v is full of zeros. Fill it up inside your loop. It's always wise to use a indexing variable as for-loop counter,
for indx=1:numel(t)
if(t(indx) <= condition)
v(indx) = some equation
elseif ...
...
end
end
get the idea?
  댓글 수: 1
Fereizqo Sulaiman
Fereizqo Sulaiman 2018년 3월 7일
No, i am trying to learn matlab by myself from a book then get stuck with this exercise. I understand, thanks for your help

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

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2018년 2월 27일
t = -5:0.5:50;
tt = [-inf,10,20,30,inf];
f = {@(t)11*t.^2 - 5*t;
@(t)1100-5*t;
@(t)50*t + 2*(t-20).^2;
@(t)1520.*exp(-.2*(t-30))};
ii = discretize(t,tt);
v = arrayfun(@(x,y)x{:}(y),f(ii),t(:));
  댓글 수: 1
Jan
Jan 2018년 3월 7일
편집: Jan 2018년 3월 7일
I have to think twice, how I can express "@(x,y)x{:}(y)" in words. :-)

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


Esha Almas
Esha Almas 2020년 3월 4일
If else by while loop

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by