How to add equation to function

조회 수: 2 (최근 30일)
Angel Hiram Torres Mota
Angel Hiram Torres Mota 2019년 6월 21일
편집: madhan ravi 2019년 6월 21일
I need to add my equation (60+(2.13*(t^2))-(0.0013*(t^4))+(0.000034*(t^4.751))) to a function but I cant figure it out. What I've tried just comes out as an error. Please help.
k=1;
for t = 0:2:100;
h(k) = (60+(2.13*(t^2))-(0.0013*(t^4))+(0.000034*(t^4.751)));
k = k+1;
if h>=0
disp(h);
end
end
This is what I tried but it doesnt work.
k=1;
for t = 0:2:100;
h(k) = rocket(t)
k = k+1;
if h>=0
disp(h);
end
end
function h(k) = rocket(t)
h(k) = (60+(2.13*(t^2))-(0.0013*(t^4))+(0.000034*(t^4.751)));
end

채택된 답변

madhan ravi
madhan ravi 2019년 6월 21일
편집: madhan ravi 2019년 6월 21일
Note: the following can be done trivially without a loop by vectorisation.
t = 0:2:100;
h=zeros(size(t));
for k=1:numel(t);
h(k) = rocket(t(k))
if h(k)>=0
disp(h(k));
end
end
function h = rocket(t)
h = (60+(2.13*(t^2))-(0.0013*(t^4))+(0.000034*(t^4.751)));
end
Without loop:
t = 0:2:100;
h = rocket(t);
fprintf('h >= 0:%f\n',h(h>=0))
function h = rocket(t)
h = (60+(2.13*(t.^2))-(0.0013*(t.^4))+(0.000034*(t.^4.751)));
end
  댓글 수: 1
Angel Hiram Torres Mota
Angel Hiram Torres Mota 2019년 6월 21일
편집: madhan ravi 2019년 6월 21일
Exactly what I was looking for, thanks!

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

추가 답변 (2개)

Star Strider
Star Strider 2019년 6월 21일
Except for your ‘rocket’ function, most of that looks as though it should work.
Leave out the subscript reference when you are declaring your function, and within your function, since ‘k’ is not defined within your function, and is not necessary anyway.
Try this instead:
function h = rocket(t)
h = (60+(2.13*(t^2))-(0.0013*(t^4))+(0.000034*(t^4.751)));
end
  댓글 수: 2
Angel Hiram Torres Mota
Angel Hiram Torres Mota 2019년 6월 21일
I wish I could accept all of the 3 answers. Thanks for the help!
Star Strider
Star Strider 2019년 6월 21일

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


Adam Danz
Adam Danz 2019년 6월 21일
편집: Adam Danz 2019년 6월 21일
Try using an anonymous function. I also cleaned up the for-loop so it is used properly.
rocketFcn = @(x)(60+(2.13*(x^2))-(0.0013*(x^4))+(0.000034*(x^4.751)));
tm = 0:2:100;
h = zeros(size(tm));
for t = 1:numel(tm)
h(t) = rocketFcn(tm(t));
if h(t)>=0
disp(h(t));
end
end
Note that I added ".^" to your rocket function. This allows you to apply vectors to its input so you can avoid the loop.
tm = 0:2:100
h2 = rocketFcn(tm);
% The two lines above produces the same output as the for-loop!
isequal(h,h2)
  댓글 수: 2
Angel Hiram Torres Mota
Angel Hiram Torres Mota 2019년 6월 21일
Thank you!
Adam Danz
Adam Danz 2019년 6월 21일
No problem! You can implement the anonymous function I suggested in madhan ravi's solution as well.

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

카테고리

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