Converting matlab m file to c file - c

I have problem to convert .m file to c class.
I want to make a ccs(code composer studio v6) project which needs a specific matrix, but the matrix is .m file(matlab data).
So, I hope to convert the matrix.m to c class.
for example: convert 1(.m data) to 2(.cpp data).
matlab
a = [1, 2 ; 3, 4];
c class
class mat{
public:
int[2][2] a;
void set(){
a[0][0] =1;
a[0][1] =2;
a[1][0] =3;
a[1][1] = 4;
}
}
In conclusion, my questions are two things.
Firstly, above conversion is possible? Is there any tool? (matrix is too large to convert by hand writing)
Secondly, are there other method to import .m file to ccs?
Thank you.

Matlab has extensive support for integration with C.
I would store the matrix to file,
and then read it using the C API provided with Matlab.
Or, if you for some reason don't want to use the Matlab API, you can create your own reader based on the mat file format specification.

Related

How transfer an array of integers from C to Matlab

Is there a somewhat easy way to transfer an array of integers from a C program to matlab? I have found several guides online on how to do it between C++ and Matlab, but not for C to Matlab.
I have several arrays of 1180 floats that I produce with a program written in C. Now I want to visualize this data in Matlab. I could have the C program export the Matlab code necessary to create the arrays hard-coded, but this seems unnecesarily devious.
I could just use the C++ method and compile my C program with a C++ compiler but at this point I am just curious if it can also be done in C.
Matlab can import .mat files, but these files seem to be encrypted or in binary format.
Please don't give suggestions on how to visualize the data in C, I have to do it in Matlab. I have a piece of code in Matlab that is returning weird results and I wrote the equivalent code in C, now I want to see if there is a difference in results. This way I can debug my Matlab code, since the end result has to be handed in in Matlab code.
My C code so far. Also I made a mistake in my initial upload, I want to transfer an array of integers.
FILE *f = fopen("Ps.bin", "wb");
for(int n = 1; n < N + 1; n++)
{
converter.asInt = Ps[n];
for(int i = 0; i < 4; i++)
{
fwrite(&converter.asBytes[i], sizeof(char), 1, f);
}
}
fclose(f);
This is what I tried in matlab, but none of it gives the proper result. In all cases matlab makes an array of doubles, which I definately don't want. It just generates an array with values that are one of these three: 0, 0.0000 and 4.925.
Ps = fread(fopen('Ps.bin'))
Ps = fread(fopen('Ps.bin'), 1180)
Ps = fread(fopen('Ps.bin'), 1180, 'uint32')
Ps = fread(fopen('Ps.bin'), 1180, '2 * uint16')
Write a binary file in C (using fwrite, look here). From matlab, you can read it using the procedure here (freadfunction)

codegen error: Conversion to struct from double is not possible

I am trying to convert Matlab legacy code into a C program. I went though the usual flows, but am having a build error that I do not understand:
Nfft = 8;
[~,coh] = size(h); // h = array of 168 elements;
display(coh); // displays 168
if mod(coh,Nfft)~=0,
h1 = [h zeros(1,Nfft-mod(coh,Nfft))];
else
h1 = h;
end
This works as expected in Matlab. But when I run it through codegen (after removing the display), I get an error at the line h1 = [h zeros(1,Nfft-mod(coh,Nfft))]; with the error message:
Conversion to struct from double is not possible.
I realize that in the matlab code, it doesn't go through this part of the code. (since 168%8 == 0).
Any ideas how to fix this?
EDIT: After some investigating, I realize that I am reading in h from a .mat file and this may be the reason. Is data read in from a .mat file considered to be a structure? If this is the case, then maybe I need to convert each element to a double first? Seems kind of hacky..
Found the solution!
When using coder.load, the .MAT file is imported as an array structure. So, in my code, I was trying to concatenate a structure with an array of doubles.
The solution to this was the way that I was loading the .MAT file:
old way:
h = coder.load('my_file.mat', 'my_file_var1');
new way:
tmp = coder.load('my_file.mat');
h = tmp.my_file_var1;
Then I was able to use h as an array of doubles.

Conjugate of a complex number in Matlab

In order to convert a Matlab code to C, I want to write it in a similar way to C first then its translation would become trivial.
I faced a problem with this line:
A = E*[SOLS' ; ones(1,10 ) ];
Where E is (9x4) real matrix and SOLS is (3x10) complex matrix. A should be a 9x10 complex matrix.
I translated this line as follows:
for i=1:9
for j=1:10
A(i,j)=E(i,1)*conj(SOLS(j,1))+E(i,2)*conj(SOLS(j,2))+E(i,3)*conj(SOLS(j,3))+ E(i,4);
end
end
I got the same result. When I replaced conj(X) by real(X)-i*imag(X)for example:
conj(SOLS(j,1)) by `real(SOLS(j,1))-imag(SOLS(j,1))*i`,
I got a wrong result and I don't understand why.
I'm doing this because in the C code, every complex number is represented by a struct with variable.re the real part and variable.im the imaginary part.
typedef struct COMPLEX{
float re;
float im;
}Complex;
I want to write a very similar matlab code to C to manipulate variables easily in C with getting a similar result with Matlab.
How to correct this please?
You are using i both as a looping index and sqrt(-1).
If you want to replace conj(SOLS(j,1)) use instead
real(SOLS(j,1))-imag(SOLS(j,1))*1i

Need suggestion on Code conversion to Matlab_extension 2

This is an extension of the previously asked question: link. In a short, I am trying to convert a C program into Matlab and looking for your suggestion to improve the code as the code is not giving the correct output. Did I convert xor the best way possible?
C Code:
void rc4(char *key, char *data){
://Other parts of the program
:
:
i = j = 0;
int k;
for (k=0;k<strlen(data);k++){
:
:
has[k] = data[k]^S[(S[i]+S[j]) %256];
}
int main()
{
char key[] = "Key";
char sdata[] = "Data";
rc4(key,sdata);
}
Matlab code:
function has = rc4(key, data)
://Other parts of the program
:
:
i=0; j=0;
for k=0:length(data)-1
:
:
out(k+1) = S(mod(S(i+1)+S(j+1), 256)+1);
v(k+1)=double(data(k+1))-48;
C = bitxor(v,out);
data_show =dec2hex(C);
has = data_show;
end
It looks like you're doing bitwise XOR on 64-bit doubles. [Edit: or not, seems I forgot bitxor() will do an implicit conversion to integer - still, an implicit conversion may not always do what you expect, so my point remains, plus it's far more efficient to store 8-bit integer data in the appropriate type rather than double]
To replicate the C code, if key, data, out and S are not already the correct type you can either convert them explicitly - with e.g. key = int8(key) - or if they're being read from a file even better to use the precision argument to fread() to create them as the correct type in the first place. If this is in fact already happening in the not-shown code then you simply need to remove the conversion to double and let v be int8 as well.
Second, k is being used incorrectly - Matlab arrays are 1-indexed so either k needs to loop over 1:length(data) or (if the zero-based value of k is used as i and j are) then you need to index data by k+1.
(side note: who is x and where did he come from?)
Third, you appear to be constructing v as an array the same size of data - if this is correct then you should take the bitxor() and following lines outside the loop. Since they work on entire arrays you're needlessly repeating this every iteration instead of doing it just once at the end when the arrays are full.
As a general aside, since converting C code to Matlab code can sometimes be tricky (and converting C code to efficient Matlab code very much more so), if it's purely a case of wanting to use some existing non-trivial C code from within Matlab then it's often far easier to just wrap it in a MEX function. Of course if it's more of a programming exercise or way to explore the algorithm, then the pain of converting it, trying to vectorise it well, etc. is worthwhile and, dare I say it, (eventually) fun.

Wrong answer in Normal Distribution in C

I have applied the normal distribution function using the equation given in this link:
http://en.wikipedia.org/wiki/Normal_distribution
I made this code for normal distribution
float m=2.0;
float s=0.5;
float x[3]={1.0, 2.0, 3.0};
float xs[3];
const float pi = 3.141;
for (int i=0; i<3; i++)
{
xs[i]=(1/s*sqrt(2*pi))*exp(-(pow(x[i]-m,2)/2*pow(s,2)));
printf("\n%f",xs[i]);
}
The answer for this code is 4.42, 5.01, 4.42
and I have the same code in Matlab
x_s_new=[1 2 3];
x_s=2+0.5.*randn(1,9);
x_s=x_s_new+0.5.*randn(1,3);
plot(x_s_new)
but the answers in matlab is 0.8 , 1.9 , 3.7
Can anyone tell me where I am going wrong?
I want to apply normal distribution using C
Thanks :)
Your Matlab code is not the analogue of your C code. The C code computes the value of the probability density function of the normal distribution at certain points. The Matlab code generates random numbers from the normal distribution.
The Matlab code corresponding to the C code is
m = 2;
s = 0.5;
x = [1 2 3];
for i = 1 : 3
xs(i) = (1/s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/2*s^2));
fprintf('%f\n',xs(i));
end
and gives the same result
4.424183
5.013257
4.424183
However, there's a mistake because / in Matlab and C only applies to the immediate next operand. Correctly it would be
xs(i) = 1/(s*sqrt(2*pi)) * exp(-( (x(i)-m)^2/(2*s^2)));
and correspondingly in C.
To translate the code using randn to C – to my knowledge there is no standard function in C to generate normally distributed random numbers, you need to find a library that includes such a function, or build it yourself starting from random().

Resources