Convert a simple C code to matlab

8 vues (au cours des 30 derniers jours)
H-H
H-H le 31 Oct 2014
Can you help to change this simple C code to matlab?
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
main(int argc, char **argv)
{
int nInputs;
double X1, X2, X3, X4, Y;
FILE *fIn = fopen(argv[1], "r");
FILE *fOut;
if (fIn == NULL)
{
printf("Simulator ERROR - cannot open in/out files.\n");
exit(1);
}
fscanf(fIn, "%d", &nInputs);
fscanf(fIn, "%lg", &X1);
fscanf(fIn, "%lg", &X2);
fscanf(fIn, "%lg", &X3);
fscanf(fIn, "%lg", &X4);
Y = 1.0 + 2 * X1 + 3.5 * X2 + 3.5 * X3 + 5 * X4;
Y += 6 * X1 * X1 + 7.5 * X1 * X2 + 7.5 * X1 * X3 + 9 * X1 * X4;
Y += 10.5 * X2 * X2 + 11 * X2 * X3 + 13 * X2 * X4;
Y += 10.5 * X3 * X3 + 13 * X3 * X4 + 15 * X4 * X4;
fOut = fopen(argv[2], "w");
fprintf(fOut, " %24.16e\n", Y);
Y = 10 + 11 * X1 + 12.5 * X2 + 12.5 * X3 + 15 * X4;
Y += 14 * X1 * X1 + 7 * X1 * X2 + 7 * X1 * X3 + 3 * X1 * X4;
Y += 4 * X2 * X2 + 8 * X2 * X3 + 5 * X2 * X4;
Y += 4 * X3 * X3 + 5 * X3 * X4 + 2 * X4 * X4;
fprintf(fOut, " %24.16e\n", Y);
fclose(fOut);
}

Réponses (1)

Abhiram Bhanuprakash
Abhiram Bhanuprakash le 31 Oct 2014
Modifié(e) : Abhiram Bhanuprakash le 31 Oct 2014
Hi H-H,
I am sorry I cannot write the code for you, but I can point to to some MATLAB functions I know which could achieve what you are looking for:
1. You need not include header files in MATLAB.
2. Instead of main() function, you can define a function in MATLAB. For more info on MATLAB functions, refer this
3. You need not declare variables in MATLAB. MATLAB creates it on-the-go.
4. You need not use pointers for file operations. You can use fread , fscanf, fwrite and a host of other Low-Level File I/O functions described here
5. For the if-else construct, use if-else in MATLAB
6. As a substitute for the 'C' function 'fprintf', you can use input. Similarly, as a substitute for the C function 'fprintf', you can use disp.
7. You cannot use the syntax '+=' in MATLAB. For a += b; you need to explicitly use
a = a+b
If you need anything more on this you can just comment on this thread, and I would be glad to help.
Hope this helps,
Cheers!
Abhiram.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by