How transfer an array of integers from C to Matlab - c

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)

Related

Converting matlab m file to c file

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.

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().

Why is mxCreateNumericMatrix maximum size smaller than system maximum array size?

I am trying to create a matrix in a MEX function. The following works:
uint64_t N;
N = 2147483647; // N = 2*2^30 -1
plhs[0] = mxCreateNumericMatrix(N,1,mxUINT8_CLASS,mxREAL);
However, I am unable to create an array that is this size:
uint64_t N;
N = 2147483648; // N = 2*2^30
plhs[0] = mxCreateNumericMatrix(N,1,mxUINT8_CLASS,mxREAL);
The preceding code throws the error:
maximum variable size allowed by the function exceeded
Which is confusing since my system (64-bit Linux running 64-bit Matlab 2010b) tells me the maximum array size is, in fact, very large.
[~,M] = computer
M =
281474976710655 % 2^48 -1 for those of you keeping track
Furthermore, from the command line, I am able to create very large arrays, and have been quite happily for some time, with calls like the following:
a = zeros(16*2^30,1,'uint8');
disp(uint64(numel(a)))
17179869184
My question is, why am I not able to create arrays in my mex function that I am clearly able to create from the command line, or from other *.m functions?
Thank you.
P.S. - I have also asked this question in the Mathworks forum. I figured I'd cast as large a net as possible. If it is answered there first, I'll post it here.
The answer lies in the compiler options. By default, Matlab limits the size to 2^31-1. To increase the size, the following option must be included in your mex compile command.
mex -largeArrayDims myFunction.c

convert a Matlab code into C code

I'm trying to understand and learn the C language, and since I used to work in Matlab, I'm interested in knowing how this code would be converted into C.
for j=1:n
v=A(:,j);
for i=1:j-1
R(i,j)=Q(:,i)'*A(:,j);
v=v-R(i,j)*Q(:,i);
end
R(j,j)=norm(v);
Q(:,j)=v/R(j,j);
end
Do you know about the Matlab Coder? Matlab can automatically generate c/c++ code for you. It has its limitations, but if are trying to learn c from Matlab, using the coder should be the best way for you to populate many examples.
Arrays are declared and accessed like so:
const int N = 10; // needs to be a constant
double v[N]; // 1-d
double A[N][N]; // 2-d
v[0] = A[1][2]; // indexing starts at 0, not 1
C doesn't do automatic vectorization like matlab, so you have to do it in for-loops manually. Instead of R(i,j)=Q(:,i)'*A(:,j),
for (int k = 0; k < N; ++k) {
R[i][j] += Q[k][i] * A[k][j];
}
That last piece also demonstrates what a for-loop looks like - the first "argument" of the "for" is the initialization of the indexing variable k, the second sets the condition under which the for loop continues, and the third increments k. The code to be executed in the loop is enclosed in braces {}.
The main logical difference is that you have to do everything element-by-element in C.

Resources