Convert a simple C code to matlab

8 ビュー (過去 30 日間)
H-H
H-H 2014 年 10 月 31 日
編集済み: Abhiram Bhanuprakash 2014 年 10 月 31 日
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);
}

回答 (1 件)

Abhiram Bhanuprakash
Abhiram Bhanuprakash 2014 年 10 月 31 日
編集済み: Abhiram Bhanuprakash 2014 年 10 月 31 日
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.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by