Finite volume method from C to MATLAB
Show older comments
Good morning everyone,
I am trying to re write my code implementing on a C compilator in MATLAB. The aim is to solve using finite volume method the equation below :
I am applying the method such that :
## Code
mandatory declarations: */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/** definition of the field h, the flux Q, time step */
double*x=NULL,*h=NULL,*Q=NULL;
double dt,L0,Delta;
double t;
int i,N;
/** Main with definition of parameters */
int main() {
L0 = 5.;
N = 128;
t=0;
Delta = L0/N;
dt =.0025;
/** dynamic allocation */
x= (double*)calloc(N+1,sizeof(double));
h= (double*)calloc(N+1,sizeof(double));
Q= (double*)calloc(N+1,sizeof(double));
/**
first cell between ‘0-Delta/2‘ and ‘0+Delta/2‘, centred in
ith cell beween ‘(i-1/2) Delta‘ (left) and ‘(i +1/2) Delta‘(right) centered in ‘(i)
*/
for(i=0;i<=N;i++)
{ x[i]=0+(i)*Delta;
h[i] = (1)*(x[i]<1);}
/** begin the time loop */
while(t<=100){
t = t + dt;
/** flux */
for(i=1;i<=N;i++)
Q[i] = - 1./3*pow(((h[i]+h[i-1])/2),3)*(h[i]-h[i-1])/Delta;
/** explicit step update and BC$$h_i^{n+1}=h_i^{n} -{\Delta t} \dfrac{F(Q_{i+1})-
for(i=1;i<N-1;i++)
h[i] += - dt* ( Q[i+1] - Q[i] )/Delta;
h[0]=h[1];
h[N]=h[N-1];
}
/** clean */
free(h);
free(Q);
free(x);
} /**
I am just wondering how to write the Q[I] line in MATLAB because h[I] depends on Q[I].
Best regards,
4 Comments
Riccardo Scorretti
on 10 May 2022
Q(i) = - 1.0/3.0* ((h(i)+h(i-1))/2.0)^3 * (h(i)-h(i-1))/Delta;
Beware of the fact that in MATLAB array index start from 1, not to 0.
Karl Zero
on 10 May 2022
Walter Roberson
on 10 May 2022
Everywhere in C that you have [index] for indexing, replace that with (index+offset) where offset = 1. You do not need to change your loop limits.
x[i]=0+(i)*Delta;
would become
x(i+offset)=0+(i)*Delta;
Karl Zero
on 11 May 2022
Answers (0)
Categories
Find more on Solver Outputs and Iterative Display in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!