Clear Filters
Clear Filters

How to convert a code from C language to Matlab?

98 views (last 30 days)
Meshooo
Meshooo on 24 Oct 2013
Commented: ad lyn on 17 Aug 2021
Dear all,
I have a code written in C language that detect the lines between cells in confocal images using the Watershed method. I want to use this C code in matlab. Is there any way to do so?
  9 Comments
otike stanley
otike stanley on 15 Apr 2021
Edited: Walter Roberson on 15 Apr 2021
Please can somebody help me convert the below Matlab algorithm to C language. I have tried several times using the Matlab Coder without success. It always return an error message, I would't know how to handle.
function theCode
%prevent scientific notation
format long
%edit filenames and sheetnames based on your application
testDataFilename = 'dataTable.xlsx';
testDataSheetName = 'modelData';
%Function of the imposition of the threshold polynomial
P = [-12.88 315.53 4900];
%get string representation and function handle to compute data for
[polyStr,Ft] = polyVector2StrAndFunc(P);
%read testData from excel file
testData = readtable(testDataFilename,'Sheet',testDataSheetName);
[testData,openCircuit,closeCircuit] = evaluateData(Ft,testData);
%write results to excel file on separate sheetname
writetable(testData,testDataFilename,'FileType','spreadsheet','Sheet',sprintf('%s_OutputResult',testDataSheetName))
%visualize result
plotFitData(P,polyStr,testData,openCircuit,closeCircuit)
function [polyStr,polyFunc] = polyVector2StrAndFunc(P)
polDegree = length(P) - 1;
polyStr = 'F(t) = ';
funcStr = '@(t)';
for p = P
if p < 0
pm = ' - ';
else
pm = ' + ';
end
if polDegree > 1
tDegStr = sprintf('t^{%d}',polDegree);
fDegStr = sprintf('t .^ %d',polDegree);
elseif polDegree == 1
tDegStr = 't';
fDegStr = tDegStr;
else
tDegStr = '';
fDegStr = '';
end
if strcmp(polyStr,'F(t) = ')
polyStr = sprintf('%s %.4f%s',polyStr,p,tDegStr);
funcStr = sprintf('%s %f ',funcStr, p);
else
polyStr = sprintf('%s %s %.4f%s',polyStr,pm,abs(p),tDegStr);
funcStr = sprintf('%s %s %f',funcStr, pm, abs(p));
end
if ~strcmp(fDegStr,'')
funcStr = sprintf('%s %s %s',funcStr, ' .* ',fDegStr);
end
%decrement degree to next level
polDegree = polDegree - 1;
end
%create function to use in computing data
% disp(funcStr)
disp(polyStr)
polyFunc = str2func(funcStr);
end
function plotFitData(P,polyStr,testData,openCircuit,closeCircuit)
figure()
hold on
legend show
plot(testData{:,'Time'},polyval(P,testData{:,'Time'}),...
'DisplayName',polyStr,'Color','k')
plot(testData{openCircuit,'Time'},testData{openCircuit,'ActivePower'}, '*',...
'DisplayName','Open Circuit Breaker', 'Color', 'r')
plot(testData{closeCircuit,'Time'},testData{closeCircuit,'ActivePower'}, 'o',...
'DisplayName','Close Circuit Breaker', 'Color', 'g')
hold off
legend('FontSize',8,'Location','northoutside')
%visualize Ft over the 24 hours period
ylabel('Power')
xlabel('Time')
end
function [testData,openCircuit,closeCircuit] = evaluateData(Ft,testData)
%compute Ft value for time data in userTable
testData{:,'Ft'} = Ft(testData{:,'Time'});
%open circuit breaker rows
openCircuit = testData{:, 'ActivePower'} > testData{:, 'Ft'};
testData(openCircuit,'REMARK') = {'Open circuit breaker'};
%close circuit breaker rows
closeCircuit = testData{:, 'ActivePower'} <= testData{:, 'Ft'};
testData(closeCircuit,'REMARK') = {'Close circuit breaker'};
end
end
Walter Roberson
Walter Roberson on 15 Apr 2021
readtable() and writetable() expand to a lot of code -- too much to convert by hand.
Graphics are not supported by MATLAB Coder. There is no C or C++ standard plotting library (there are several competing standards, including DirectX and OpenGL and Metal)

Sign in to comment.

Answers (23)

Azzi Abdelmalek
Azzi Abdelmalek on 24 Oct 2013
Look at mex files
  2 Comments
Meshooo
Meshooo on 24 Oct 2013
Thank you very much but I wonder if there is more straightforward way/software to do that in easy way. Do you think matlab compiler can do that automatically?
Azzi Abdelmalek
Azzi Abdelmalek on 24 Oct 2013
Matlab compiler allows to create an executable file from your m code; while Matlab coder convert your m code to c or c++ code. Mex files allows to run your c++ or fortran files in Matlab environment, but no m code is generated.

Sign in to comment.


zhao
zhao on 24 Oct 2013
I guess no direct way to do that. I am considering convert matlab code to C. This should be easier, but it is still not good.
  2 Comments
Machine Learning Enthusiast
What is the procedure for coverting Matlab code to C?
Walter Roberson
Walter Roberson on 27 Oct 2016
MATLAB Coder can convert (some) MATLAB code to C.

Sign in to comment.


Walter Roberson
Walter Roberson on 27 Oct 2016
If you compile the C to a DLL, you can use loadlibrary()
Note: historically, Unix .o files were (are?) in the same format as .so (shared object) so historically you did not always have to run a link phase, if you had a single .o .

N/A
N/A on 28 Nov 2017
Edited: Walter Roberson on 28 Nov 2017
while(true~=1)
for i=0; i<25; i+1;
for j=0; j<25 ; j+1;
if s[i]=s[j] && i~=j
match[k]=s[i];
k=k+1;
if s[i]~=s[j] && i~=j
true=0;
end
end
end
end
end
how to convert this to mathlab
  2 Comments
Walter Roberson
Walter Roberson on 28 Nov 2017
flagtrue = 0;
while (flagtrue~=1)
i = 0;
while i < 25
j = 0;
while j < 25
s(i+1) = s(j);
if s(i+1) ~= 0 && i ~= j
flagtrue = 0;
end
j + 1; %not sure why you bother to add 1 to j and discard the result
end
i + 1; %not sure why you bother to add 1 to i and discard the result
end
end
This is the equivalent MATLAB. It is an infinite loop, because the original code is an infinite loop (for multiple reasons).
Hari Priya
Hari Priya on 27 Mar 2019
Edited: Walter Roberson on 5 May 2019
#include<stdio.h>
#include<math.h>
int main()
{
float x1,y1,x2,y2,vx,vy,len,x3,y3,size;
vx=x1-x2;
vy=y1-y2;
len=sqrt((vx*vx)+(vy*vy));
x3=vx/((len*size)+x1);
y3=vy/((len*size)+y1);
float temp1,temp2,angle;
temp1=y3-y1;
temp2=x3-x1;
angle=atan2(temp1,temp2)+1.57;
return 0;
}
I want to Convert this code into matlab code sir

Sign in to comment.


dania mohammed
dania mohammed on 28 Jan 2018
Edited: Walter Roberson on 28 Jan 2018
BEGIN {
highest_packet_id = 0;
}
{
action = $1;
time = $3;
#from = $3;
#to = $4;
type = $35; #aodv relationships,if 5 no infomation
pktsize = $37;
#src = $9;
#dst = $10;
#seq_no = $11;
packet_id = $41;
if ( type != "AODV" ) {
if ( packet_id > highest_packet_id )
highest_packet_id = packet_id;
if ( start_time[packet_id] == 0 )
if ( type == "cbr" && action != "d" ) {
if ( action == "r" ) {
end_time[packet_id] = time;
}
} else {
end_time[packet_id] = -1;
}
}
}
END {
for ( packet_id = 0; packet_id <= highest_packet_id; packet_id++ ) {
start = start_time[packet_id];
end = end_time[packet_id];
packet_duration = end - start;
if ( start < end ) printf("%f %f\n", start, packet_duration);
}
}
please anyone help me
I need convert this code to matlab
how I can get it???
  1 Comment
Walter Roberson
Walter Roberson on 28 Jan 2018
Edited: Walter Roberson on 28 Jan 2018
Which AWK version do you need this to conform with?
This code has no direct translation in MATLAB, because this code assumes "standard input", which MATLAB does not have. The MATLAB version would need to be told which file to open.
Are you aware that you can invoke perl from MATLAB? And there is an AWK to Perl convertor: http://perldoc.perl.org/a2p.html

Sign in to comment.


Hoang Kien
Hoang Kien on 11 Mar 2018
Edited: Hoang Kien on 11 Mar 2018
lease anyone help me I need convert this code to matlab how I can get it???
#include <stdio.h>
#include <conio.h>
void main()
{
int n, a, c, i, j;
int h, k;
int hs[36], hsc[36], hsd[36];
printf("Bien doi dang Da thuc.\n");
printf("Chuan tac suy rong sang chuan tac suy rong.\n");
printf("Nhap n, a va h: ");
scanf("%d" "%d" "%d", &n, &a, &h);
printf("Nhap c va k: ");
scanf("%d" "%d", &c, &k);
hsd[n]=0;
for(i=0; i<= n; i++){
printf("Nhap vao he so a%d: ",i);
scanf("%d", &hs[i]);}
printf("\n%5s"," ");
for (i=n; i>=0; i--){
printf("%5d ", hs[i]);}
for (j=0;j<n;j++){
for (i=n-1;i>=j;i--){
hsc[j]=c+(j*k);
hsd[i]=(hsc[j]-a+((j-i)*h)); //hsd[i]=(c+(j*k)-a+((j-i)*h));
hs[i]=hs[i]+hs[i+1]*hsd[i]; //hs[i]=hs[i]+hs[i+1]*(c+(j*k)-a+((j-i)*h));}
printf("\n%5s"," ");
for (i=n; i>=j; i--){
printf("%5d ", hsd[i]);}
printf("\n%5d",hsc[j]);
for (i=n; i>=j; i--){
printf("%5d ", hs[i]);}}
printf("\n\nVoi c = %d va k = %d, cac he so cua da thuc moi la:\n",c,k);
for (i=0; i<=n; i++){
printf("%5d ", hs[i]);}
getch();}
  4 Comments
Walter Roberson
Walter Roberson on 7 Feb 2021
Edited: Walter Roberson on 8 Feb 2021
The below code needs to be reviewed, as it does not do exactly the same thing that the C code does.
  1. The C expression for m involved taking the square root of S1 and immediately squaring that, and adding to that the squares of S2 and S3. That seems very unlikely to be what is wanted: it is much more likely that you would square S1, S2, and S3, add those squares, and take the square root of that.
  2. The C expressions for calculating R and G were each missing ) and so would have failed to compile. I had to guess where the ) went by analogy to the calculation for B.
  3. The C expression for writing the output file would fail to compile, or if it compiled would either crash or do a random thing. This is because the fprintf used a file identifier named RGB, which is not a defined variable in the program. The below MATLAB code is therefore different because it actually writes the variables to a file.
  4. C does not use ** for exponentation. C has no exponentation operator and uses the pow() function instead. Your code would not have compiled in C.
The C code seems to be intended to write to a file named 'RGB.xls' but it does so as tab delimited text. This is confusing, and is likely to cause problems. I would recommend that you either write it to a true .xls file or that you write it to a .tsv or .txt file. To write it to a true .xls file, use writematrix(RGB, 'RGB.xls') with no further options. To write it to a .tsv or .txt file, change the file extension in the writematrix() call I provided.
There is another difference with the code I provided: I read and output the entire input files, not just the first n points of it.
In future, when you ask people to convert code for you, you should make sure that it is working code, so that they do not have to make guesses about what the code is intended to do.
S = fileread('I1Q1.bin');
IQ1 = sscanf(S, '%f');
S = fileread('I2Q2.bin');
IQ2 = sscanf(S, '%f');
I1 = IQ1(1:2:end);
Q1 = IQ2(2:2:end);
I2 = IQ2(1:2:end);
Q2 = IQ2(2:2:end);
A = I1.^2 + Q1.^2;
B = I2.^2 + Q2.^2;
S0 = A + B;
S1 = A - B;
S2 = 2 * (I1 .* I2 + Q1 .* Q2);
S3 = 2 * (Q1 .* I2 - Q2 .* I1);
m = sqrt(S1.^2 + S2.^2 + S3.^2)/S0; %CHECK THIS!!! (1)
delta = atan2(S3,S2);
R = sqrt(S0 .* m .* (1+sin(delta)/2)); %CHECK THIS!!! (2)
G = sqrt(S0 .* m .* (1-sin(delta)/2)); %CHECK THIS!!! (2)
B = sqrt(S0*(1-m));
RGB = [R(:), G(:), B(:)];
writematrix(RGB, 'RGB.xls', 'filetype', 'text', 'delimiter', '\t'); %CHECK THIS!!! (3)

Sign in to comment.


Barenya Bikash  Hazarika
Barenya Bikash Hazarika on 20 Jun 2018
Can anybody convert this C Code to matlab?
#include<stdio.h>
#define MAX_SIZE 5
int main()
{
int arr[MAX_SIZE]; %Declare an array of MAX_SIZE
int i,j, N;
// Input array size
printf("Enter size of array: ");
scanf("%d", &N);
// Input elements in array
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
// Print all elements of array
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
for(j=i; j<N; j++)
{
printf("%d, ", arr[i,j]);
}
printf("\n");
}
return 0;
}
  3 Comments
leo john
leo john on 3 Mar 2020
Kindly help sir how to do scanf in array using for loop
#include<stdio.h>
#define MAX_SIZE 5
int main()
{
int arr[MAX_SIZE]; %Declare an array of MAX_SIZE
int i,j, N;
// Input array size
printf("Enter size of array: ");
scanf("%d", &N);
// Input elements in array
printf("Enter %d elements in the array : ", N);
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
// Print all elements of array
printf("\nElements in array are: ");
for(i=0; i<N; i++)
{
printf("%d, ", arr[i]);
}
return 0;
}
Walter Roberson
Walter Roberson on 3 Mar 2020
MATLAB does not have any equivalent to scanf(). scanf() reads from standard input but MATLAB does not have standard input. The closest MATLAB has is to use input() with the 's' option and sscanf() the resulting character vector.

Sign in to comment.


kavan dave
kavan dave on 8 Jul 2018
public void BlogECGExample()
{
// Define your own dataDir
var dataDir = "................";
// Load ECG wave from physionet.org data file.
string filename = Path.Combine( dataDir, "ECG_AAMIEC13.data.txt" );
string line;
int cnt = 0;
FloatVector ecgMeasurement = new FloatVector( 3000 );
var fileStrm = new System.IO.StreamReader( filename );
fileStrm.ReadLine(); fileStrm.ReadLine();
while ( ( line = fileStrm.ReadLine() ) != null && cnt < 3000 )
{
ecgMeasurement[cnt] = Single.Parse( line.Split( ',' )[1] );
cnt++;
}
// Choose wavelet
var wavelet = new FloatWavelet( Wavelet.Wavelets.D4 );
// Build DWT object
var dwt = new FloatDWT( ecgMeasurement.DataBlock.Data, wavelet );
// Decompose signal with DWT to level 5
dwt.Decompose( 5 );
// Find Universal threshold & threshold all detail levels with lambdaU
double lambdaU = dwt.ComputeThreshold( FloatDWT.ThresholdMethod.Universal, 1 );
dwt.ThresholdAllLevels( FloatDWT.ThresholdPolicy.Soft, new double[] { lambdaU, lambdaU, lambdaU, lambdaU, lambdaU } );
// Rebuild the signal to level 1 - the original (filtered) signal.
float[] reconstructedData = dwt.Reconstruct();
// Display DWT results.
BlogECGExampleBuildCharts( dwt, ecgMeasurement, reconstructedData );
}
public void BlogECGExampleBuildCharts( FloatDWT dwt, FloatVector ECGMeasurement, float[] ReconstructedData )
{
// Plot out approximations at various levels of decomposition.
var approxAllLevels = new FloatVector();
for ( int n = 5; n > 0; n-- )
{
var approx = new FloatVector( dwt.WaveletCoefficients( DiscreteWaveletTransform.WaveletCoefficientType.Approximation, n ) );
approxAllLevels.Append( new FloatVector( approx ) );
}
var detailsAllLevels = new FloatVector();
for ( int n = 5; n > 0; n-- )
{
var approx = new FloatVector( dwt.WaveletCoefficients( DiscreteWaveletTransform.WaveletCoefficientType.Details, n ) );
detailsAllLevels.Append( new FloatVector( approx ) );
}
// Create and display charts.
Chart chart0 = NMathChart.ToChart( detailsAllLevels );
chart0.Titles.Add( "Concatenated DWT Details to Level 5" );
chart0.ChartAreas[0].AxisY.Title = "DWT Details";
chart0.Height = 270;
NMathChart.Show( chart0 );
Chart chart1 = NMathChart.ToChart( approxAllLevels );
chart1.Titles.Add("Concatenated DWT Approximations to Level 5");
chart1.ChartAreas[0].AxisY.Title = "DWT Approximations";
chart1.Height = 270;
NMathChart.Show( chart1 );
Chart chart2 = NMathChart.ToChart( (new FloatVector( ReconstructedData ))[new Slice(500,500)] );
chart2.Titles[0].Text = "Thresholded & Reconstructed ECG Signal";
chart2.ChartAreas[0].AxisY.Title = "mV";
chart2.Height= 270;
NMathChart.Show( chart2 );
Chart chart3 = NMathChart.ToChart( (new FloatVector( ECGMeasurement ))[new Slice(500,500)] );
chart3.Titles[0].Text = "Raw ECG Signal";
chart3.ChartAreas[0].AxisY.Title = "mV";
chart3.Height = 270;
NMathChart.Show( chart3 );
}
Can you please tell me how to convert this code into matlab code? what to write in place of public void ()
  1 Comment
Walter Roberson
Walter Roberson on 8 Jul 2018
In MATLAB, the equivalent of
public void BlogECGExample()
is
function BlogECGExample
with the code stored in BlogECGExample.m

Sign in to comment.


Mahboubeh Parastarfeizabadi
Edited: Walter Roberson on 27 Jul 2018
Can anyone helping me to convert this C code to Matlab:
#include "FFilter.h"
static int filter_taps[FFILTER_TAP_NUM] = {
158,
2,
2,
1,
1,
1,
0,
0,
-1,
-2,
-2,
-3,
-5,
-6,
-7,
-9,
-10,
-12,
-14,
-15,
-18,
-20,
-22,
-24,
-26,
-29,
-31,
-34,
-36,
-39,
-41,
-44,
-46,
-48,
-50,
-52,
-53,
-55,
-56,
-57,
-58,
-58,
-58,
-57,
-57,
-56,
-54,
-52,
-50,
-47,
-44,
-41,
-37,
-33,
-28,
-23,
-18,
-12,
-7,
-1,
6,
12,
18,
25,
31,
38,
44,
51,
57,
63,
69,
74,
80,
84,
89,
93,
97,
100,
103,
105,
106,
107,
108,
108,
107,
106,
104,
102,
99,
96,
92,
88,
84,
78,
73,
67,
61,
55,
48,
42,
35,
28,
21,
14,
7,
0,
-7,
-13,
-20,
-26,
-31,
-37,
-42,
-47,
-51,
-55,
-59,
-62,
-65,
-67,
-69,
-70,
-71,
-71,
-71,
-70,
-69,
-68,
-66,
-64,
-62,
-59,
-56,
-53,
-50,
-46,
-43,
-39,
-35,
-31,
-28,
-24,
-21,
-18,
-15,
-12,
-9,
-7,
-5,
-4,
-2,
-2,
-1,
-1,
-2,
-2,
-4,
-5,
-7,
-10,
-12,
-15,
-19,
-22,
-26,
-30,
-34,
-38,
-43,
-47,
-51,
-55,
-59,
-63,
-66,
-69,
-72,
-75,
-77,
-78,
-79,
-80,
-80,
-79,
-78,
-76,
-74,
-71,
-67,
-63,
-58,
-53,
-47,
-40,
-34,
-26,
-19,
-11,
-2,
6,
15,
23,
32,
41,
49,
58,
66,
74,
82,
89,
96,
102,
108,
113,
117,
121,
124,
126,
128,
128,
129,
128,
127,
124,
122,
118,
114,
110,
104,
99,
93,
86,
80,
73,
66,
58,
51,
44,
37,
30,
24,
18,
12,
7,
2,
-2,
-5,
-8,
-10,
-12,
-12,
-12,
-11,
-10,
-7,
-4,
-1,
4,
9,
14,
20,
27,
34,
41,
48,
55,
63,
70,
77,
84,
91,
97,
102,
107,
111,
114,
117,
118,
118,
117,
115,
111,
106,
100,
93,
84,
74,
62,
49,
35,
20,
3,
-14,
-33,
-53,
-73,
-94,
-116,
-138,
-161,
-184,
-206,
-229,
-252,
-274,
-295,
-316,
-336,
-354,
-372,
-388,
-402,
-415,
-426,
-436,
-443,
-448,
-450,
-451,
-449,
-445,
-438,
-429,
-417,
-403,
-386,
-367,
-346,
-322,
-297,
-269,
-239,
-208,
-175,
-140,
-104,
-67,
-29,
9,
49,
88,
128,
167,
206,
245,
283,
319,
355,
389,
421,
452,
480,
507,
531,
552,
571,
588,
601,
612,
619,
624,
625,
624,
619,
612,
601,
588,
571,
552,
531,
507,
480,
452,
421,
389,
355,
319,
283,
245,
206,
167,
128,
88,
49,
9,
-29,
-67,
-104,
-140,
-175,
-208,
-239,
-269,
-297,
-322,
-346,
-367,
-386,
-403,
-417,
-429,
-438,
-445,
-449,
-451,
-450,
-448,
-443,
-436,
-426,
-415,
-402,
-388,
-372,
-354,
-336,
-316,
-295,
-274,
-252,
-229,
-206,
-184,
-161,
-138,
-116,
-94,
-73,
-53,
-33,
-14,
3,
20,
35,
49,
62,
74,
84,
93,
100,
106,
111,
115,
117,
118,
118,
117,
114,
111,
107,
102,
97,
91,
84,
77,
70,
63,
55,
48,
41,
34,
27,
20,
14,
9,
4,
-1,
-4,
-7,
-10,
-11,
-12,
-12,
-12,
-10,
-8,
-5,
-2,
2,
7,
12,
18,
24,
30,
37,
44,
51,
58,
66,
73,
80,
86,
93,
99,
104,
110,
114,
118,
122,
124,
127,
128,
129,
128,
128,
126,
124,
121,
117,
113,
108,
102,
96,
89,
82,
74,
66,
58,
49,
41,
32,
23,
15,
6,
-2,
-11,
-19,
-26,
-34,
-40,
-47,
-53,
-58,
-63,
-67,
-71,
-74,
-76,
-78,
-79,
-80,
-80,
-79,
-78,
-77,
-75,
-72,
-69,
-66,
-63,
-59,
-55,
-51,
-47,
-43,
-38,
-34,
-30,
-26,
-22,
-19,
-15,
-12,
-10,
-7,
-5,
-4,
-2,
-2,
-1,
-1,
-2,
-2,
-4,
-5,
-7,
-9,
-12,
-15,
-18,
-21,
-24,
-28,
-31,
-35,
-39,
-43,
-46,
-50,
-53,
-56,
-59,
-62,
-64,
-66,
-68,
-69,
-70,
-71,
-71,
-71,
-70,
-69,
-67,
-65,
-62,
-59,
-55,
-51,
-47,
-42,
-37,
-31,
-26,
-20,
-13,
-7,
0,
7,
14,
21,
28,
35,
42,
48,
55,
61,
67,
73,
78,
84,
88,
92,
96,
99,
102,
104,
106,
107,
108,
108,
107,
106,
105,
103,
100,
97,
93,
89,
84,
80,
74,
69,
63,
57,
51,
44,
38,
31,
25,
18,
12,
6,
-1,
-7,
-12,
-18,
-23,
-28,
-33,
-37,
-41,
-44,
-47,
-50,
-52,
-54,
-56,
-57,
-57,
-58,
-58,
-58,
-57,
-56,
-55,
-53,
-52,
-50,
-48,
-46,
-44,
-41,
-39,
-36,
-34,
-31,
-29,
-26,
-24,
-22,
-20,
-18,
-15,
-14,
-12,
-10,
-9,
-7,
-6,
-5,
-3,
-2,
-2,
-1,
0,
0,
1,
1,
1,
2,
2,
158
};
void FFilter_init(FFilter* f) {
int i;
for(i = 0; i < FFILTER_TAP_NUM; ++i)
f->history[i] = 0;
f->last_index = 0;
}
void FFilter_put(FFilter* f, int input) {
f->history[f->last_index++] = input;
if(f->last_index == FFILTER_TAP_NUM)
f->last_index = 0;
}
int FFilter_get(FFilter* f) {
long long acc = 0;
int index = f->last_index, i;
for(i = 0; i < FFILTER_TAP_NUM; ++i) {
index = index != 0 ? index-1 : FFILTER_TAP_NUM-1;
acc += (long long)f->history[index] * filter_taps[i];
};
return acc >> 16;
}
#ifndef FFILTER_H_
#define FFILTER_H_
/*
FIR filter designed with
http://t-filter.appspot.com
sampling frequency: 2000 Hz
fixed point precision: 16 bits
* 0 Hz - 10 Hz
gain = 0
desired attenuation = -40 dB
actual attenuation = n/a
* 13 Hz - 30 Hz
gain = 1
desired ripple = 5 dB
actual ripple = n/a
* 33 Hz - 1000 Hz
gain = 0
desired attenuation = -40 dB
actual attenuation = n/a
*/
#define FFILTER_TAP_NUM 723
typedef struct {
int history[FFILTER_TAP_NUM];
unsigned int last_index;
} FFilter;
void FFilter_init(FFilter* f);
void FFilter_put(FFilter* f, int input);
int FFilter_get(FFilter* f);
#endif

Cristian Macavei
Cristian Macavei on 3 Jan 2019
Can someone help me convert this to matlab please?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.1415926535897
#endif
int main()
{
int n;
float proiectieX[100], proiectieY[100];
printf("Numar de vectori: ");
scanf("%d" , &n);
for(int i = 1; i <= n ; ++i)
{
float theta;
float modul;
printf("Modulul vectorului %d si unghiul dintre Ox si vector in grade:", i);
scanf("%f %f", &modul, &theta);
if(modul < 0) continue;
theta = (theta * M_PI) / 180.0f;
proiectieX[i] = cos(theta) * modul;
proiectieY[i] = sin(theta) * modul;
}
for (int i = 1; i <= n; ++i)
{
printf("Proiectiile vectorului %d : %g %g \n", i, proiectieX[i], proiectieY[i]);
}
return 0;
}
  3 Comments
pallavi sapkale
pallavi sapkale on 22 Feb 2019
please convert this c code in matlab...........
/* Includes the library functions of C */
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
/* Declaration of Global Variables for time control of Simulation */
time_t start, end;
/* For scaling the time in order quicked the simulation */
int scale_time = 0;
int scale_measure = 0;
/* Seed for generating random numbers */
long *seed;
/* For keeping count of the changes to different networks and time
spent in each network */
int count_wlan = 0;
int count_cdma = 0;
int wlan_cdma = 0;
/* Opens the file for writing the solution */
FILE *fpt = fopen("SimulationResults.txt", "wb");
60
/* Function for reading data from file */
int readln(FILE *fp, char *ch)
{
char c;
int i = 0;
if (fread(&c, 1, 1, fp)<1)
return 0;
while (c=='\n' || c=='\r' || c==' ')
if (fread(&c, 1, 1, fp)<1)
return 0;
while (!(c=='\n' || c == '\r'))
{
*ch = c;
ch++;
i++;
if (fread(&c, 1, 1, fp)<1)
return 0;
}
*ch=0;
return 1;
}
/* END readln */
/* Random number generator functions */
/******************************************************************
Function: rndnum
Portable uniform (0,1) random number generator. Uses the
multiplicative congruential method:
z(i)=(7**5*z(i-1))(mod 2**31 - 1)
Ref : Law & Kelton, SIMULATION MODELING AND ANALYSIS,
McGraw Hill, 1982, p. 227.
******************************************************************/
double rndnum(
long *seed ) /* long integer seed (by reference) */
{
static long a = 16807;
static long b15 = 32768;
static long b16 = 65536;
static long p = 2147483647;
static long xhi, xalo, leftlo, fhi, k;
static double lawkel;
xhi = *seed/b16;
xalo = ( *seed - xhi * b16) * a;
leftlo = xalo / b16;
fhi = xhi * a + leftlo;
k = fhi / b15;
*seed = ( ( ( xalo - leftlo * b16 ) - p )+( fhi - k * b15 ) * b16 ) +
k;
if ( *seed < 0 ) *seed = *seed + p;
lawkel = *seed * 4.656612875e-10;
return lawkel;
}
61
/******************************************************************
Function: drand
Generate a (continuous) uniform random variable in the
interval [a,b] using a passed seed. Returns the value.
******************************************************************/
double drand(
double a, /* low end of the range */
double b, /* high end of the range */
long *seed ) /* long integer seed (by reference) */
{
double value;
value = (a + (b - a) * rndnum(seed));
return value;
}
/******************************************************************
Function: irand
Generate an integer uniform random variable in the (integer)
interval [a,b] using a passed seed. Returns the value.
******************************************************************/
int irand(
int a, /* low end of the range */
int b, /* high end of the range */
long *seed ) /* long integer seed (by reference) */
{
int trial;
trial = a + (int) ( (b - a + 1) * rndnum(seed) );
if (trial > b)
{
trial = b;
}
return trial;
}
/* Declaration of functions that will be used */
int loop_wlan(double Chi_thresh, int real_time, int lambda_r, int
lambda_n, int Num_RSS, double RSS, int NEARWLAN, int lambda_u, int
Sim_time, int Mea_time);
int loop_cdma(int NEARWLAN, double Chi_thresh, int lambda_u, int Num_RSS,
double RSS, int real_time, int lambda_r, int lambda_n, int Sim_time, int
Mea_time);
int loop_cdma1(int NEARWLAN, double Chi_thresh, int lambda_u, int
Num_RSS, double RSS, int real_time, int lambda_r, int lambda_n, int
Sim_time, int Mea_time);
/* Main starts here */
int main()
{
62
/* Declaration of Variables and Parameters */
double RSS = 0;
double Chi_thresh = 0;
int Num_RSS = 0;
int WORKWLAN = 0;
int NEARWLAN = 0;
int real_time = 0;
int lambda = 0;
int lambda_r = 0;
int lambda_n = 0;
int lambda_u = 0;
int Sim_time = 0;
int Mea_time = 0;
Walter Roberson
Walter Roberson on 22 Feb 2019
You should start a new question for this.
Is it necessary to duplicate the same random number generators for compatibility, or could you just use rand() and irand()?
Does the implementation of readln() have to be bug-for-bug compatible, or could you just use fgetl() ?
We will need to know exactly which compiler and compiler release this code is intended for, in order to figure out how to deal with the 62 that is hanging there at the beginning of main(). That is not legal C or C++, but since compilers are permitted to make extensions, maybe it is an instruction to the compiler about linkage properties, or maybe it is a machine code instruction that is to be inserted.

Sign in to comment.


EROL EREN GÖZLÜ
EROL EREN GÖZLÜ on 5 May 2019
#include <math.h>
#include <stdio.h>
/*********************************************************************
*
*
* Name: mag_est.c
*
* Synopsis:
*
* Demonstrates and tests the "Alpha * Min + Beta * Max" magnitude
* estimation algorithm.
*
* Description:
*
* This program demonstrates the "Alpha, Beta" algorithm for
* estimating the magnitude of a complex number. Compared to
* calculating the magnitude directly using sqrt(I^2 + Q^2), this
* estimation is very quick.
*
* Various values of Alpha and Beta can be used to trade among RMS
* error, peak error, and coefficient complexity. This program
* includes a table of the most useful values, and it prints out the
* resulting RMS and peak errors.
*
* Copyright 1999 Grant R. Griffin
*
* The Wide Open License (WOL)
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without
* fee, provided that the above copyright notice and this license
* appear in all source copies. THIS SOFTWARE IS PROVIDED "AS IS"
* WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. See
* http://scopeplot.com/dg/wol.htm for more information.
*
*********************************************************************/
/********************************************************************/
double alpha_beta_mag(double alpha, double beta, double inphase,
double quadrature)
{
/* magnitude ~= alpha * max(|I|, |Q|) + beta * min(|I|, |Q|) */
double abs_inphase = fabs(inphase);
double abs_quadrature = fabs(quadrature);
if (abs_inphase > abs_quadrature) {
return alpha * abs_inphase + beta * abs_quadrature;
} else {
return alpha * abs_quadrature + beta * abs_inphase;
}
}
/*********************************************************************/
double decibels(double linear)
{
#define SMALL 1e-20
if (linear <= SMALL) {
linear = SMALL;
}
return 20.0 * log10(linear);
}
/*********************************************************************/
void test_alpha_beta(char *name, double alpha, double beta,
int num_points)
{
#define PI 3.141592653589793
int ii;
double phase, real, imag, err, avg_err, rms_err;
double peak_err = 0.0;
double sum_err = 0.0;
double sum_err_sqrd = 0.0;
double delta_phase = (2.0 * PI) / num_points;
for (ii = 0; ii < num_points; ii++) {
phase = delta_phase * ii;
real = cos(phase);
imag = sin(phase);
err = sqrt(real * real + imag * imag)
- alpha_beta_mag(alpha, beta, real, imag);
sum_err += err;
sum_err_sqrd += err * err;
err = fabs(err);
if (err > peak_err) {
peak_err = err;
}
}
avg_err = sum_err / num_points;
rms_err = sqrt(sum_err_sqrd / num_points);
printf("%-16s %14.12lf %14.12lf %9.6lf %4.1lf %4.1lf\n",
name, alpha, beta, avg_err, decibels(rms_err),
decibels(peak_err));
}
/*********************************************************************/
void main(void)
{
#define NUM_CHECK_POINTS 100000
typedef struct tagALPHA_BETA {
char *name;
double alpha;
double beta;
} ALPHA_BETA;
#define NUM_ALPHA_BETA 16
const ALPHA_BETA coeff[NUM_ALPHA_BETA] = {
{ "Min RMS Err", 0.947543636291, 0.3924854250920 },
{ "Min Peak Err", 0.960433870103, 0.3978247347593 },
{ "Min RMS w/ Avg=0", 0.948059448969, 0.3926990816987 },
{ "1, Min RMS Err", 1.0, 0.323260990 },
{ "1, Min Peak Err", 1.0, 0.335982538 },
{ "1, 1/2", 1.0, 1.0 / 2.0 },
{ "1, 1/4", 1.0, 1.0 / 4.0 },
{ "Frerking", 1.0, 0.4 },
{ "1, 11/32", 1.0, 11.0 / 32.0 },
{ "1, 3/8", 1.0, 3.0 / 8.0 },
{ "15/16, 15/32", 15.0 / 16.0, 15.0 / 32.0 },
{ "15/16, 1/2", 15.0 / 16.0, 1.0 / 2.0 },
{ "31/32, 11/32", 31.0 / 32.0, 11.0 / 32.0 },
{ "31/32, 3/8", 31.0 / 32.0, 3.0 / 8.0 },
{ "61/64, 3/8", 61.0 / 64.0, 3.0 / 8.0 },
{ "61/64, 13/32", 61.0 / 64.0, 13.0 / 32.0 }
};
int ii;
printf("\n Alpha * Max + Beta * Min Magnitude Estimator\n\n");
printf("Name Alpha Beta Avg Err RMS Peak\n");
printf(" (linear) (dB) (dB)\n");
printf("---------------------------------------------------------------------\n");
for (ii = 0; ii < NUM_ALPHA_BETA; ii++) {
test_alpha_beta(coeff[ii].name, coeff[ii].alpha, coeff[ii].beta, 1024);
}
}
Can anyone convert this code into matlab please?
  1 Comment
Walter Roberson
Walter Roberson on 5 May 2019
You should start a new Question for that. When you do, I recommend that you post your attempt at the conversion, and post particular questions you have such as error messages you encountered.

Sign in to comment.


MADHUMITHA M
MADHUMITHA M on 28 May 2019
can we able to convert this into MATLAB
#include <stdint.h>
static inline uint64_t rotl(const uint64_t x, int k)
{
return (x << k) | (x >> (64 - k));
}
static uint64_t s[2];
uint64_t next(void) {
const uint64_t s0 = s[0];
uint64_t s1 = s[1];
const uint64_t result = s0 + s1;
s1 ^= s0;
s[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16); // a, b
s[1] = rotl(s1, 37); // c
return result;
}
void jump(void) {
static const uint64_t JUMP[] = { 0xdf900294d8f554a5, 0x170865df4b3201fc };
uint64_t s0 = 0;
uint64_t s1 = 0;
for(int i = 0; i < sizeof JUMP / sizeof *JUMP; i++)
for(int b = 0; b < 64; b++) {
if (JUMP[i] & UINT64_C(1) << b) {
s0 ^= s[0];
s1 ^= s[1];
}
next();
}
s[0] = s0;
s[1] = s1;
}
/* This is the long-jump function for the generator. It is equivalent to
2^96 calls to next(); it can be used to generate 2^32 starting points,
from each of which jump() will generate 2^32 non-overlapping
subsequences for parallel distributed computations. */
void long_jump(void) {
static const uint64_t LONG_JUMP[] = { 0xd2a98b26625eee7b, 0xdddf9b1090aa7ac1 };
uint64_t s0 = 0;
uint64_t s1 = 0;
for(int i = 0; i < sizeof LONG_JUMP / sizeof *LONG_JUMP; i++)
for(int b = 0; b < 64; b++) {
if (LONG_JUMP[i] & UINT64_C(1) << b) {
s0 ^= s[0];
s1 ^= s[1];
}
next();
}
s[0] = s0;
s[1] = s1;
}
  8 Comments
Walter Roberson
Walter Roberson on 19 Jul 2019
To use the below, call myrand() and assign the result to a variable. The result will be a struct with three fields, "next", "jump", and "long_jump", each a function handle. Invoke the function handles out of the struct. For example,
mr = myrand();
val = mr.next();
mr.long_jump();
The below code is untested.
%the "myrand" prefix was used in the below code to avoid naming a function "next"
%to avoid classes with MATLAB's next loop control.
function funs = myrand()
funs.next = @myrand_next;
funs.jump = @myrand_jump;
funs.long_jump = @myrand_long_jump;
persistent s;
s = zeros(1,2,'uint64');
function result = myrand_rotl(x, k)
assert( isa(x, 'uint64') )
result = bitor( x .* 2.^k, x ./ 2.^(64 - k));
end
function result = myrand_leftshift(x, k)
%C++ << operator loses bits at the top, but MATLAB saturates
assert( isa(x, 'uint64') )
mask = intmax('uint64')./(2.^k) - 1;
result = bitand( x, mask ) * 2.^k;
end
function result = myrand_next()
s0 = s(1);
s1 = s(2);
result = s0 + s1;
s1 = bitxor(s1, s0);
s(1) = bitxor(bitxor(myrand_rotl(s0, 24), s1), myrand_leftshift(s1, 16)); %// a, b
s(2) = myrand_rotl(s1, 37); %// c
end
function myrand_jump()
JUMP = sscanf('0xdf900294d8f554a5 0x170865df4b3201fc', '%lx %lx');
s0 = uint64(0);
s1 = uint64(0);
for i = 1:length(JUMP)
for b = 0 : 63
if bitget(JUMP(i), b+1)
s0 = bitxor(s0, s(1));
s1 = bitxor(s1, s(2));
end
myrand_next();
end
end
s(1) = s0;
s(2) = s1;
end
%{
/* This is the long-jump function for the generator. It is equivalent to
2^96 calls to next(); it can be used to generate 2^32 starting points,
from each of which jump() will generate 2^32 non-overlapping
subsequences for parallel distributed computations. */
%}
function myrand_long_jump
LONG_JUMP = sscanf('d2a98b26625eee7b dddf9b1090aa7ac1', '%lx %lx');
s0 = uint64(0);
s1 = uint64(1);
for i = 1 : length(LONG_JUMP)
for b = 0 : 63
if bitget(LONG_JUMP(i), b+1)
s0 = bitxor(s0, s(1));
s1 = bitxor(s1, s(2));
end
myrand_next();
end
end
s(1) = s0;
s(2) = s1;
end
end
Madhumitha Munusamy
Madhumitha Munusamy on 19 Aug 2019
Thank you so much sir.
I will run the code and let you know the output

Sign in to comment.


RUBEN NAHUE
RUBEN NAHUE on 8 Jun 2019
Edited: Walter Roberson on 22 Aug 2020
HELLO PLEASE COULD HELP ME HOW TO CONVERT THIS CODE TO MATLAB.
function[L1;L2;U1;U2] = Cholesky(a; b; c)
n = length(a);
Diagonales = zeros(1; n);
Sub = zeros(1; n - 1);
if a(1) > 0 then
Diagonales(1) = sqrt(a(1));
Sub(1) = b(1)/Diagonales(1);
k = 2;
fin = 0;
while k <= n ^ fin == 0 do
if a(k) - Sub(k - 1)^2 > 0 then
Diagonales(k) = sqrt(a(k) - Sub(k -1)^2);
if Diagonales(k) = 0 ^ k < n then
Sub(k) = b(k)/Diagonales(k);
else if Diagonales(k) == 0 then
fprintf('Division por cero')
fin = 1;
end if
else
fprintf('Division por cero')
fin = 1;
end if
k = k + 1
end while
fprintf('Valor negativo en la posicion (1), no se puede ejecutar el metodo')
end if
  2 Comments
Walter Roberson
Walter Roberson on 8 Jun 2019
That is not C code. It is a language similar to Maple but it is not Maple.
Walter Roberson
Walter Roberson on 8 Jul 2019
If you were to use the original and change the ^ in the if tests to & then it might possibly work as Octave code.

Sign in to comment.


Madhumitha Munusamy
Madhumitha Munusamy on 23 Sep 2019
i am having a little problem over here. can someone help me
i have a OFDM matlab code. In that i want to replace cyclic prefix by NPR filter to analyze the performance but it's showing error.
below i have given both my matlab code and filter

NIPUNA RAVEENDRAN
NIPUNA RAVEENDRAN on 13 Feb 2020
Can anybody convert this C Code to matlab?
// 2D HYBRID MEDIAN FILTER implementation
// image - input image
// result - output image
// N - width of the image
// M - height of the image
void _hybridmedianfilter(const element* image, element* result, int N, int M)
{
// Move window through all elements of the image
for (int m = 1; m < M - 1; ++m)
for (int n = 1; n < N - 1; ++n)
{
element window[5];
element results[3];
// Pick up cross-window elements
window[0] = image[(m - 1) * N + n];
window[1] = image[m * N + n - 1];
window[2] = image[m * N + n];
window[3] = image[m * N + n + 1];
window[4] = image[(m + 1) * N + n];
// Get median
results[0] = median(window, 5);
// Pick up x-window elements
window[0] = image[(m - 1) * N + n - 1];
window[1] = image[(m - 1) * N + n + 1];
window[2] = image[m * N + n];
window[3] = image[(m + 1) * N + n - 1];
window[4] = image[(m + 1) * N + n + 1];
// Get median
results[1] = median(window, 5);
// Pick up leading element
results[2] = image[m * N + n];
// Get result
result[(m - 1) * (N - 2) + n - 1] = median(results, 3);
}
}
  1 Comment
Walter Roberson
Walter Roberson on 13 Feb 2020
%// 2D HYBRID MEDIAN FILTER implementation
%// image - input image
%// result - output image
%// N - width of the image
%// M - height of the image
function result = hybridmedianfilter(image, N, M)
%// Move window through all elements of the image
for m = 1: M-2
for n = 1: N-2
% Pick up cross-window elements
window(0+1) = image((m - 1) * N + n + 1);
window(1+1) = image(m * N + n - 1 + 1);
window(2+1) = image(m * N + n + 1);
window(3+1) = image(m * N + n + 1 + 1);
window(4+1) = image((m + 1) * N + n + 1);
%// Get median
results(0+1) = median(window);
%// Pick up x-window elements
window(0+1) = image((m - 1) * N + n - 1 + 1);
window(1+1) = image((m - 1) * N + n + 1 + 1);
window(2+1) = image(m * N + n + 1);
window(3+1) = image((m + 1) * N + n - 1 + 1);
window(4+1) = image((m + 1) * N + n + 1 + 1);
%// Get median
results(1+1) = median(window);
%// Pick up leading element
results(2+1) = image(m * N + n + 1);
%// Get result
result((m - 1) * (N - 2) + n - 1 + 1) = median(results);
end
end
Note that median() is not part of C or C++. This matters because some common implementations of median() do not use the same order or meaning of parameters, so we have to guess about which implementation you are using and what the meaning of the parameters is.
In practice no-one would write code this way.
In practice there is a significant chance that this code will not do what you want unless you import a whole bunch of other code that stores arrays in the same order as is used here.

Sign in to comment.


Josias Sandoval
Josias Sandoval on 31 May 2020
Can anybody convert this C Code to matlab please?
#include <stdio.h>
#include <stdlib.h>
FILE *f1,*f2;
int Vth=10,s=0,d=0;
void aztec (int Vth) { /* Entrada, thresold */
enum {PLATEAU,SLOPE};
long Vmx,Vmn,Vmxi,Vmni;
int V,
LineMode=PLATEAU, /* Indica modo Plateau o Slope */
LineLen=1,
V1,
T1,
Vsi,
Tsi,
Sign,
AZT;
int count=0,np=0,ns=0,sp=0,ss=0;
fscanf (f1,"%x\n",&V);
count++;
Vmni=Vmxi=V;
AZT=V;
LineMode=PLATEAU;
while (!feof (f1)) {
while (LineLen<51) {
LineLen++;
if (feof (f1)) break;
fscanf (f1,"%x\n",&V);
count++;
Vmx=Vmxi;
Vmn=Vmni;
if (Vmx<V) Vmxi=V;
if (Vmn>V) Vmni=V;
if ((Vmxi-Vmni)>=Vth) break;
}
T1=LineLen-1;
V1=(Vmx+Vmn)>>1;
if (LineMode==PLATEAU) {
if (T1>2) {
fprintf (f2,"%04x\n",T1);
fprintf (f2,"%04x\n",V1);
sp+=T1; np++;
AZT=V1;
}
else {
LineMode=SLOPE;
if ((V1-AZT)<0) Sign=-1;
else Sign=1;
Tsi=T1;
Vsi=V1;
}
}
else {
if (T1>2) {
fprintf (f2,"%04x\n",-Tsi);
fprintf (f2,"%04x\n",Vsi);
fprintf (f2,"%04x\n",T1);
fprintf (f2,"%04x\n",V1);
sp+=T1; np++;
ss+=Tsi; ns++;
AZT=V1;
LineMode=PLATEAU;
}
else {
if (((V1-Vsi)*Sign)<0) {
fprintf (f2,"%04x\n",-Tsi);
fprintf (f2,"%04x\n",Vsi);
ss+=Tsi; ns++;
AZT=Vsi;
Tsi=T1;
Vsi=V1;
Sign*=-1;
}
else {
Tsi+=T1;
Vsi=V1;
}
}
}
Vmxi=Vmni=V;
LineLen=1;
}
printf ("\nNúmero de muestras tratadas: %d",count);
printf ("\nNúmero de líneas generadas : %5d\tsuma: %d",np,sp);
printf ("\nNúmero de rampas generadas : %5d\tsuma: %d",ns,ss);
}
  3 Comments
Josias Sandoval
Josias Sandoval on 1 Jun 2020
I don't know but I found the code in this pdf page 96 of the book
Walter Roberson
Walter Roberson on 2 Jun 2020
When I go through that code, it appears to me as if the code is designed to fetch its input from the C25 and send the input to somewhere I cannot tell at the moment. But it is not clear at all from the code; it just relies upon two files already being open (or connected).
Is your purpose to talk to a C25 to do real-time EEG compression? As that is what the whole premise is, real-time compression. Or do you have files of EEG input that you want to apply their AZTEC algorithm to? If so then what is the input format?
I do not want to go through the trouble of loading the development system to work through the meaning of some of the less clear parts of the code. The device was current more than 20 years ago; I doubt I could run the development system on my Mac, and I do not have one of the devices and I do not have the peripherals needed to test with.
I would suggest that you use the ideas described, and the block diagram in order to write the code from scratch, for use on EEG files that you already have. I can see from the code that the AZTEC algorithm is intended for use only on a single input channel, so you might also want to enhance it to handle multiple channels.

Sign in to comment.


Bayu Setiaji
Bayu Setiaji on 14 Jun 2020
Dear all,
I have a code written in C language that detect the lines between cells in confocal images using the Watershed method. I want to use this C code in matlab. Is there any way to do so?
static void Main(string[] args)
{
Random random = new Random();
int counter = 0;
double deviasi = 50;
double mean = 1000;
double[] data = { 0.0, 0.0 };
while (counter < 2) {
double rand = random.NextDouble();
double y = deviasi * rand + mean;
if (y >= 999.5) {
if (y <= 1000.5) {
data[counter] = y;
counter++;
}
}
}
Console.WriteLine(data[0]+" "+ data[1]);
Console.ReadKey();
}
  1 Comment
Walter Roberson
Walter Roberson on 27 Jun 2020
counter = 1;
deviasi = 50;
mean = 1000;
data = [0. 0.];
while counter <= 2
y = deviasi * rand + mean;
if y >= 999.5 && y <= 1000.5
data(counter) = y;
counter = counter + 1;
end
end
fprintf('%g %g\n', data);
pause()

Sign in to comment.


Ta Huu Tai
Ta Huu Tai on 27 Jun 2020
Edited: Walter Roberson on 27 Jun 2020
You can fix it for me??
clear;
clc;
delete(instrfind);
figure;
for theta=0:1:180
for i=1:1:50
x1(i)=i*cos(theta*3.14/180);
y1(i)=i*sin(theta*3.14/180);
end
plot(0,0,x1,y1,'color','g','LineWidth',10);
hold on;
end
xlabel('Distance (cm)');
for R=10:10:50
k=1;
for i=0:1:180
x(k)=R*cos(i*3.14/180);
y(k)=R*sin(i*3.14/180);
k=k+1;
end
plot(x,y,'color','k','LineWidth',4);
hold on;
end
for theta=0:30:180
for i=1:1:50
x11(i)=i*cos(theta*3.14/180);
y11(i)=i*sin(theta*3.14/180);
end
plot(0,0,x11,y11,'color','k','LineWidth',4);
hold on;
end
labels=cellstr(num2str([0:30:180]'));
text([50*cos(0);50*cos(3.18/6);50*cos(2*3.18/6);50*cos(3*3.18/6);50*cos(4*3.18/6);50*cos(5*3.18/6);50*cos(3.18)],[50*sin(0);50*sin(3.18/6);50*sin(2*3.18/6);50*sin(3*3.18/6);50*sin(4*3.18/6);50*sin(5*3.18/6);50*sin(3.18)],labels,'BackgroundColor',[.7 .9 .7]);
s=serial('COM10');
s.BaudRate=9600;
fopen(s);
while(1)
if (fscanf(s,'%f')=='.')==[1 0 0]
angle=fscanf(s,'%f');
distance=fscanf(s,'%f');
elseif (fscanf(s,'%f')=='.')==[1 0 0]
angle=fscanf(s,'%f');
distance=fscanf(s,'%f');
else
fscanf(s,'%f');
angle=fscanf(s,'%f');
distance=fscanf(s,'%f');
end
if distance>50
distance=50;
end
x3=distance*cos(angle*3.14/180);
y3=distance*sin(angle*3.14/180);
x4=50*cos(angle*3.14/180);
y4=50*sin(angle*3.14/180);
x5=distance*cos((angle+2)*3.14/180);
y5=distance*sin((angle+2)*3.14/180);
x6=50*cos((angle+2)*3.14/180);
y6=50*sin((angle+2)*3.14/180);
x7=distance*cos((angle-2)*3.14/180);
y7=distance*sin((angle-2)*3.14/180);
x8=50*cos((angle-2)*3.14/180);
y8=50*sin((angle-2)*3.14/180);
x9=distance*cos((angle+3)*3.14/180);
y9=distance*sin((angle+3)*3.14/180);
x10=50*cos((angle+3)*3.14/180);
y10=50*sin((angle+3)*3.14/180);
x11=distance*cos((angle-3)*3.14/180);
y11=distance*sin((angle-3)*3.14/180);
x12=50*cos((angle-3)*3.14/180);
y12=50*sin((angle-3)*3.14/180);
X3=distance*cos(angle*3.14/180);
Y3=distance*sin(angle*3.14/180);
X4=50*cos(angle*3.14/180);
Y4=50*sin(angle*3.14/180);
X5=0;
Y5=0;
X6=50*cos((angle+2)*3.14/180);
Y6=50*sin((angle+2)*3.14/180);
X7=0;
Y7=0;
X8=50*cos((angle-2)*3.14/180);
Y8=50*sin((angle-2)*3.14/180);
X9=0;
Y9=0;
X10=50*cos((angle+3)*3.14/180);
Y10=50*sin((angle+3)*3.14/180);
X11=0;
Y11=0;
X12=50*cos((angle-3)*3.14/180);
Y12=50*sin((angle-3)*3.14/180);
hold on;
n=plot([X3,X4,X5,X6,X7,X8,X9,X10,X11,X12],[Y3,Y4,Y5,Y6,Y7,Y8,Y9,Y10,Y11,Y12],'color','y','LineWidth',20);
m=plot([x3,x4,x5,x6,x7,x8,x9,x10,x11,x12],[y3,y4,y5,y6,y7,y8,y9,y10,y11,y12],'color','r','LineWidth',20);
drawnow;
delete(m,n);
end
fclose(s);
Matlab said :
Warning: Unsuccessful read: Matching failure in format..
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..
Warning: File 'm,n' not found.
> In Untitled (line 94)
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..
Error using ==
Matrix dimensions must agree.
Error in Untitled (line 38)
if (fscanf(s,'%f')=='.')==[1 0 0]
  2 Comments
Walter Roberson
Walter Roberson on 27 Jun 2020
if (fscanf(s,'%f')=='.')==[1 0 0]
Caution: fscanf() on a serial port by default reads until the first terminator is encountered or the end of the input buffer is reached. In a number of places in your code, you are assuming that fscanf(s,'%f') returns a particular size of input. If you have reason to expect a particular number of inputs on one line, I recommend that you use fgetl() to fetch a line, and then sscanf() the line to read the items. I recommend that you continually cross-check that the number of items you receive is the same as the number you expect, and that you have active error handling.
When you work with serial ports, it is common for the communications stream to get out of synchronization with what you expect.

Sign in to comment.


Mehmet
Mehmet on 22 Aug 2020
Edited: Mehmet on 22 Aug 2020
Hello all, I have code written in C language and I need to convert it to matlab. Can anyone help me for that?
#include <stdio.h>
#include <math.h>
#define PI 3.14
void calculate(int r1, int r2, int h);
int main()
{
int r1, r2, h;
printf("Enter a r1 value: ");
scanf("%d", &r1);
printf("Enter a r2 value: ");
scanf("%d", &r2);
for(h = 1; h < 10; h++){
calculate(r1, r2, h);
}
return 0;
}
void calculate(int r1, int r2, int h)
{
double volume, surfaceArea;
volume = PI * h * (r1 + r2) / 3;
printf("Volume for %d is %f \n", h, volume);
surfaceArea = PI * (r1-2) * sqrt((pow((r2 + r1), 2)) + pow(h, 2)) + PI * pow(r1, 2);
printf("Surface area for %d is %f", h, surfaceArea);
}
  4 Comments
Walter Roberson
Walter Roberson on 22 Aug 2020
Edited: Walter Roberson on 22 Aug 2020
Using a more accurate value for Pi would make it a different program...
The second part of the code I posted is copied and pasted from the C code; the first part is just some shims to make the second part work.
Mehmet
Mehmet on 23 Aug 2020
thank you all very much. I also think the formula is wrong, but it was written like this on the paper.

Sign in to comment.


Ali Abdualaziz
Ali Abdualaziz on 27 Sep 2020
Can anybody convert this C Code to matlab please?
Int I, j, k, m=4, n=2;
Float x(float t;), xs[n*m],p[m],xa[m][n],ya[m][n],f=1000, fs=8000;
X(t)=sin(2*pi*f*t);
For(i=1;i<=m*n;i++)
Xs[i]=x(i/fs);
For(j=1;j<=m;j++)
For(k=1;k<=n;k++)
Xa[j][k]=xs[j*k];
For(j=1;j<=m;j++)
P[j]=scanf(“enter %d th slice”,j);
For(j=1;j<=m;j++)
For(k=1;k<=n;k++)
Ya[j][k]=xa[p[j]][k];
  3 Comments
Walter Roberson
Walter Roberson on 27 Sep 2020
Float x(float t;)
If we assume that somehow the first character of each line got mangled in posting and should be lowercase instead of uppercase, then
float x(float t;)
However, in C, there cannot be any semi-colon inside a type declaration.
If we assume further that the semi-colon was a typing mistake and the real code was
float x(float t)
then that would declare that you want to use an external function named x that accepts a float parameter and returns a float parameter.
X(t)=sin(2*pi*f*t);
Assuming again that the first character has been accidentally upper-cased,
x(t)=sin(2*pi*f*t);
That would be invalid. You declared x as being a external function, but you cannot assign to functions in C. If you wanted to define x then you would have had to use
float x(float t) {
return sin(2*pi*f*t);
}
and that would have to be separated from the type declarations of the line
Float x(float t;), xs[n*m],p[m],xa[m][n],ya[m][n],f=1000, fs=8000;

Sign in to comment.


Maria Imdad
Maria Imdad on 8 Oct 2020
Edited: Walter Roberson on 8 Oct 2020
Hi,
This is c Code for "Tiny Encryption Algorithm" can some one please help me to convert it into matlab..
I will be very thankful.
[code deleted -- WDR]
  1 Comment
Walter Roberson
Walter Roberson on 8 Oct 2020
Sorry, Maria Imdad:
For legal reasons we are not permitted to discuss encryption here.

Sign in to comment.


Tala sh
Tala sh on 1 Jun 2021
Edited: Tala sh on 1 Jun 2021
Hi, please can somebody help me to convert this code from C language to Matlab?
///function for encoding textfile
int RleEncodeFile(FILE *inFile, FILE *outFile)
{
int currChar; /* current characters */
int prevChar; /* previous characters */
unsigned char count; /* number of characters in a run */
/* validate input and output files */
if ((NULL == inFile) || (NULL == outFile))
{
errno = ENOENT;
return -1;
}
/* encode inFile */
prevChar = EOF; /* force next char to be different */
count = 0;
/* read input until there's nothing left */
while ((currChar = fgetc(inFile)) != EOF)
{
fputc(currChar, outFile);
/* check for run */
if (currChar == prevChar)
{
/* we have a run. count run length */
count = 0;
while ((currChar = fgetc(inFile)) != EOF)
{
if (currChar == prevChar)
{
count++;
if (count == UCHAR_MAX)
{
/* count is as long as it can get */
fputc(count, outFile);
/* force next char to be different */
prevChar = EOF;
break;
}
}
else
{
/* run ended */
fputc(count, outFile);
fputc(currChar, outFile);
prevChar = currChar;
break;
}
}
}
else
{
/* no run */
prevChar = currChar;
}
if (currChar == EOF)
{
/* run ended because of EOF */
fputc(count, outFile);
break;
}
}
return 0;
}
///function for decoding text file
int RleDecodeFile(FILE *inFile, FILE *outFile)
{
int currChar; /* current characters */
int prevChar; /* previous characters */
unsigned char count; /* number of characters in a run */
/* validate input and output files */
if ((NULL == inFile) || (NULL == outFile))
{
errno = ENOENT;
return -1;
}
/* decode inFile */
prevChar = EOF; /* force next char to be different */
/* read input until there's nothing left */
while ((currChar = fgetc(inFile)) != EOF)
{
fputc(currChar, outFile);
/* check for run */
if (currChar == prevChar)
{
/* we have a run. write it out. */
count = fgetc(inFile);
while (count > 0)
{
fputc(currChar, outFile);
count--;
}
prevChar = EOF; /* force next char to be different */
}
else
{
/* no run */
prevChar = currChar;
}
}
return 0;
}
  8 Comments