Using embedded matlab funciton to find high accuracy derivative

조회 수: 1 (최근 30일)
Hi, I want to use embedded matlab function to take a high accuracy derivative of a sin wave. I have used sine wave block from simulink library, with 101 samples per period, 0 offset, 1 amplitude and sample time of 0.01. The solver is configured as fixed step solver (ode 4) with the same step size of 0.01. The simulation time is set as 1 sec.
The sine signal is named as B and here is the code I am using in the embedded funciton block. The formula for the derevative that I want to use uses central difference technique and is as follows.
B'(n))=(-B(n+2)+8B(n+1)-8B(n-1)+B(n-2))/(12.*step size); where, B is the input signal, n is the current time step I have successfuly tested the formula using command line and script and it is working, but when I use the same code in embedded matlab function, I get out of bounds error.
Here is the code that I am using:
function D = fcn(B) D=zeros (101,1); for n=3:99 D(n)=(-B(n+2)+8.*B(n+1)-8.*B(n-1)+B(n-2))./(12.*0.01); end This is the error message that I receive: Runtime error: Index into array out of range Attempted to access 5 element of data B. The valid index range is 1 to 1. I think it is due to the signal size problem, but I dont know how to fix it. Please help me, I will really appreciate you help! Thanks

채택된 답변

Titus Edelhofer
Titus Edelhofer 2012년 4월 23일
Hi,
this is a misunderstanding of how Simulink works: Simulink computes every timestep on it's own. So when your embedded MATLAB function block get's called the input is the input from one single step (index range is 1, as the error says), not all 101 values.
So: for the time step at time T you don't have the input values of T+h, T+2h! These are values from the "future". You will have to use backward differencing (and use some default values for the history for T=0, T=h) if you want to use the embedded MATLAB function block.
Titus
  댓글 수: 3
Titus Edelhofer
Titus Edelhofer 2012년 4월 23일
Hi Amir,
you will use UnitDelay blocks to get the output of the sine at T-h, T-2h (just add another UnitDelay). The have an initial condition (which you probably best leave as zero).
Titus
Amir Khan
Amir Khan 2012년 5월 16일
Thanks Titus! Really appreciate your help!

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by