How to index a value of an anonymous function
7 ビュー (過去 30 日間)
古いコメントを表示
I am trying to create a function that uses Euler Method to find the height of water in a tank as a function of time given the equation for dy/dt. The equation dy/dt is to be passed into my function as an anonymous function. The equation for dy/dt depends on both y and t as well as some constants.
My program initilizes a vector called change that I want to store the values of dy/dt as the loop runs. I cannot run the program as it is given because I am trying to store each value of dy/dt (which should be calculated on each iteration based on the changing value of y as the loop runs) to be multiplied by the timestep, but the value of the vector called 'change' is remaining constant. What I essentially want to do is have 'change(k)=dydt(k)' but because I am passing dydt as an anonymous function using 'y' as an input I cannot simply index using '(k)' at the end of the vector name the way I usually would. I'm not sure if there is an easy fix or if I need to re-program the way the way I am using the anonymous function. Any tips and help are appriciated, thank you!!
function [depth_vector] = Depth_Calc(dydt,i,f,n,varargin)
%Calculates the Depth vs Time by evaluating the differential
%equation y with parameters A, Q, alpha from time i to time f
%using timestep n and generates table printout of results
%input:
%dydt= function (given as anonymous function)
%i=initial time
%f=finl time
%n=timestep
t=[i:n:f];
y=ones(1,((f-i)/n));
change=.32635*ones(1,((f-i)/n));
for k=2:((f-i)/n)
change=dydt(varargin{:})
y(k)=y(k-1)+n*change(k-1);
end
depth_vector=y;
output=depth_vector;
2 件のコメント
KSSV
2020 年 10 月 29 日
You want change to be a matrix? According to your code y also will be a matrix.
採用された回答
Ameer Hamza
2020 年 10 月 29 日
The exact solution depends on what are the input arguments of dydt, but if it is defined as an anonymous function, then you should be able to do something like this inside the for-loop
change(k) = dydt(varargin{:})
6 件のコメント
Ameer Hamza
2020 年 10 月 30 日
I don't think that is the issue. Following code works just fine for me
dydt=@(t,y,A,Q,a) 3*(Q/A).*((sin(t)).^2)-(a.*((1+y).^1.5))./A;
A=1300 ; Q=450 ; a=150;
Depth_Calc(dydt, 1, 10, 1, A, Q, a)
Can you show the lines of code that causes this error?
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!