How to convert a code from C language to Matlab

29 ビュー (過去 30 日間)
EROL EREN GÖZLÜ
EROL EREN GÖZLÜ 2019 年 5 月 5 日
編集済み: Walter Roberson 2022 年 1 月 14 日
#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);
}
}
  4 件のコメント
Guillaume
Guillaume 2019 年 5 月 6 日
@erol, why can't you convert it yourself. There is nothing complicated about that code. You can pretty much rewrite as matlab code by copying most of it. If there's a few things you don't understand you can search for it with your favorite search engine or ask here.
More importantly, why do you want to convert it. The main of the program has fixed inputs and will always produce the same output. That doesn't strike me as very useful.
EROL EREN GÖZLÜ
EROL EREN GÖZLÜ 2019 年 5 月 6 日
Thanks for your comments

サインインしてコメントする。

採用された回答

Jan
Jan 2019 年 5 月 6 日
編集済み: Jan 2019 年 5 月 6 日
Try this one - it is not debugged and written in the forum's interface:
function main
NUM_CHECK_POINTS = 100000;
coeff = { ...
'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};
fprintf('\n Alpha * Max + Beta * Min Magnitude Estimator\n\n');
fprintf('Name Alpha Beta Avg Err RMS Peak\n');
fprintf(' (linear) (dB) (dB)\n');
printf('---------------------------------------------------------------------\n');
for ii = 1:size(coeff, 1)
test_alpha_beta(coeff{ii, 1}, coeff{ii, 2}, coeff{ii, 3}, 1024);
end
end
function R = alpha_beta_mag(alpha, beta, inphase, quadrature)
% magnitude ~= alpha * max(|I|, |Q|) + beta * min(|I|, |Q|) */
abs_inphase = abs(inphase);
abs_quadrature = abs(quadrature);
if abs_inphase > abs_quadrature
R = alpha * abs_inphase + beta * abs_quadrature;
else
R = alpha * abs_quadrature + beta * abs_inphase;
end
end
function R = decibels(linear)
R = 20.0 * log10(max(1e-20, linear));
end
function R = test_alpha_beta(name, alpha, beta, num_points)
peak_err = 0.0;
sum_err = 0.0;
sum_err_sqrd = 0.0;
delta_phase = (2.0 * Ppi) / num_points;
for ii = 0:num_points - 1
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 = sum_err + err;
sum_err_sqrd = sum_err_sqrd + err * err;
err = abs(err);
if (err > peak_err)
peak_err = err;
end
end
avg_err = sum_err / num_points;
rms_err = sqrt(sum_err_sqrd / num_points);
fprintf('%-16s %14.12f %14.12f %9.6f %4.1f %4.1f\n',
name, alpha, beta, avg_err, decibels(rms_err),
decibels(peak_err));
end
It took 2 minutes to convert is from C to Matlab.
  1 件のコメント
EROL EREN GÖZLÜ
EROL EREN GÖZLÜ 2019 年 5 月 6 日
Thank you very much Jan I appreciate

サインインしてコメントする。

その他の回答 (1 件)

Dilshana O
Dilshana O 2021 年 6 月 7 日
Hei plzz convert this c code into matlab code #include<stdio.h> void main(){
float p1,p2,p3; float delta=1; scanf("%f%f%f",&p1,&p2,&p3); float d = p2; if(p1 != p2) { if(p1>p2) { if(p2>p3) { d=d-delta; delta=delta*2; } else if(p2=p3) { d=d-delta; delta=delta*2; } else { delta=delta/2; } } else { if(p3>p2) { d=d+delta; delta=delta*2; } else if(p2=p3) { d=d+delta; delta=delta*2; } else { delta=delta/2; } } } else if(p1==p2) { if(p2>p3) { if(p2>p3) { d=d-delta; delta=delta/2; } else if(p2<p3) { d=d-delta; delta=delta*2; } else { delta=delta*2; } } }
}
  3 件のコメント
Mohsen momenitabar
Mohsen momenitabar 2022 年 1 月 14 日
編集済み: Walter Roberson 2022 年 1 月 14 日
Hi Everyone, I have a c++ code and i need to convert it to MATLAB code. Here is my code:
Thanks,
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(list, val) memset(list, (val), sizeof(list))
#define pb push_back
typedef vector<int> _Route;
typedef vector<vector<int> > _RouteSet;
typedef vector<vector<double> > Matrix;
#define MAX 200
#define INF 1e8
enum status {NEW_ROUTE_ADDED, SIZE_OVERFLOW, NO_PATH};
int minRouteSize, maxRouteSize;
vector<double> popularity;
struct node{
int id;
double dist;
node(int i, double w){
id = i;
dist = w;
}
friend bool operator<(const node& l, const node& r)
{
return l.dist > r.dist; // since default pq is max pd
}
};
void readData(string filename, Matrix &matrix)
{
FILE *fp = fopen(filename.c_str(), "r");
int siz, num;
fscanf(fp, "%d", &siz);
vector<double> temp;
for(int i=0; i<siz; i++){
for(int j=0; j<siz; j++){
fscanf(fp, "%d", &num);
temp.push_back((double)num);
}
matrix.push_back(temp);
temp.clear();
}
fclose(fp);
}
template<class T>
void print_matrix(vector<vector<T> > &m)
{
int d = m.size();
for(int i = 0; i < d; i++) {
int l = m[i].size();
for(int j = 0; j < l; j++) {
printf("%f ", m[i][j]);
}
printf("\n");
}
}
pair<int, int> getHighestDemandPair(Matrix &demand)
{
int from, to;
double maxDemand = 0;
for(int i=0; i<demand.size(); i++){
for(int j=0; j<demand[i].size(); j++){
if(demand[i][j] > maxDemand){
from = i, to = j, maxDemand = demand[i][j];
}
}
}
//cout << "check: " << from << ' ' << to << ' ' << maxDemand << endl;
return make_pair(from, to);
}
int highestDemandDestination(int from, Matrix &demand)
{
int ret;
double maxDemand = -INF;
for(int i=0; i<demand[from].size(); i++){
if(demand[from][i] > maxDemand){
maxDemand = demand[from][i];
ret = i;
}
}
return ret;
}
double normalize(Matrix &mat)
{
double mx = 0;
for(int i=0; i<mat.size(); i++){
auto it = max_element(begin(mat[i]), end(mat[i]));
mx = max(mx, *it);
}
if(mx == 0) return 0;
for(int i=0; i<mat.size(); i++){
for(int j=0; j<mat[i].size(); j++){
if(mat[i][j] == -1 || mat[i][j] == 0) mat[i][j] = INF; ///for no edge case
else mat[i][j] /= mx;
}
}
return mx;
}
status getBestRoute(int from, int to, Matrix &distance, Matrix &demand, _Route &ret, double dw)
{
//cout << "from: " << from << " to: " << to << " demand: " << demand[from][to] << endl;
Matrix tempDist = distance, tempDemand = demand;
normalize(tempDemand); ///normalize demands
normalize(tempDist); ///normalize distance
///transform to fit shortest path problem
for(int i=0; i <tempDist.size(); i++) {
for(int j=0; j<tempDist[i].size(); j++) {
if(tempDist[i][j] <= 1.0) tempDist[i][j] = (1 - dw) * tempDist[i][j] + dw * 0.5 * (1/(tempDemand[i][to]+1) + 1/(tempDemand[j][to]+1));
}
}
int numberOfNodes = distance.size();
double djDist[numberOfNodes+1], parent[numberOfNodes+1];
for(int i=0; i<numberOfNodes; i++){
djDist[i] = INF;
parent[i] = -1;
}
djDist[from] = 0; ///path cost = distance + 1/(demand + 1)
priority_queue<node> Q;
Q.push(node(from, djDist[from]));
bool dequed[numberOfNodes+1];
mem(dequed, false);
while(!Q.empty()){
int fr = Q.top().id;
//cout << fr <<endl;
if(fr == to) break;
if(dequed[fr]){
Q.pop();
continue;
}
djDist[fr] = Q.top().dist;
dequed[fr] = true;
Q.pop();
for(int i=0; i<tempDist[fr].size(); i++){
if(tempDist[fr][i] >= 1e6 || fr == i) continue;
if(djDist[i] > djDist[fr] + tempDist[fr][i]){
djDist[i] = djDist[fr] + tempDist[fr][i];
parent[i] = fr;
Q.push(node(i, djDist[i]));
}
}
}
if(parent[to] == -1){ //no path
//cout << "no path\n";
return NO_PATH;
}
_Route temp;
int cur = to;
temp.push_back(cur);
while(cur != from){
cur = parent[cur];
temp.push_back(cur);
}
//for(int i=temp.size()-1; i>=0; i--) cout << temp[i] << ' ' ;
//cout << endl;
if(ret.size() + temp.size() -1 <= maxRouteSize){
assert(temp.size() != maxRouteSize + 1);
if(ret.size()) ret.pop_back();
ret.insert(ret.end(), temp.rbegin(), temp.rend());
return NEW_ROUTE_ADDED;
}
return SIZE_OVERFLOW;
}
bool recur(Matrix &distance, Matrix &demand, Matrix &choice, _Route &route, double dw, int from, int to = -1) ///generates a single route
{
//getchar();
if(choice[from][to] <= 0 || demand[from][to] <= 0){
//cout << "No demand left\n";
return (route.size() >= minRouteSize && route.size() <= maxRouteSize); ///no more demand left
}
status ret = getBestRoute(from, to, distance, demand, route, dw); ///add a route (part)
if(ret == SIZE_OVERFLOW){
//cout << "size overflow\n";
return (route.size() >= minRouteSize && route.size() <= maxRouteSize);
}
if(ret == NO_PATH){
//cout << "no path between " << from << ' ' << to << " demand: " << choice[from][to] << endl;
choice[from][to] = 0;
choice[to][from] = 0;
to = highestDemandDestination(from, choice);
return recur(distance, demand, choice, route, dw, from, to);
}
//segment added to route
//cout << "route segment added\ncurrent size: " << route.size() << endl;
for(int i=0; i<route.size(); i++){
for(int j=0; j<route.size(); j++){
demand[route[i]][route[j]] = 0;
choice[route[i]][route[j]] = 0;
}
}
for(int i=0; i<route.size(); i++){
int ind = route[i];
for(int j=0; j<distance[ind].size(); j++) distance[j][ind] = -1;
}
from = to;
to = highestDemandDestination(from, choice);
return recur(distance, demand, choice, route, dw, from, to);
}
void getBestRouteSet(Matrix &dist, Matrix &demand, int numberOfRoutes, _RouteSet &RS, double dw)
{
//puts("Inside genBestRouteSet");
Matrix tempDist, tempDemand = demand, choice;
for(int i=0; i<numberOfRoutes; i++){
tempDist = dist;
choice = tempDemand;
pair<int, int> pp = getHighestDemandPair(choice);
int from = pp.first, to = pp.second;
if(popularity[from] > popularity[to]) swap(from, to);
_Route route;
bool added = recur(tempDist, tempDemand, choice, route, dw, from, to);
if(!added) i--;
else{
//cout << "route added\n";
RS.push_back(route);
}
}
///getHighestDemandPair(tempDemand);
}
bool checkRoute(const _Route &route, const Matrix &distance, int maxRouteSize, int minRouteSize)
{
/*
if(route.size() > maxRouteSize)
return false;
if(route.size() < minRouteSize)
return false;
*/
assert(route.size() >= minRouteSize && route.size() <= maxRouteSize);
int n = distance.size();
vector<bool> isInRoute(n, false);
for(int i = 0; i < route.size(); i++) {
/*
if(isInRoute[route[i]]) {
return false;
}
*/
assert(!isInRoute[route[i]]);
isInRoute[route[i]] = true;
}
for(int i = 0; i < route.size() - 1; i++) {
/*
if(distance[route[i]][route[i + 1]] == -1) {
return false;
}
*/
assert(distance[route[i]][route[i + 1]] != -1);
}
return true;
}
int main(int argc, char **argv)
{
if(argc < 7) {
printf("Usage: distances_file demands_file num_of_routes minRouteSize maxRouteSize num_of_route_sets\n");
return 1;
}
Matrix dist, demand;
readData(argv[1], dist);
readData(argv[2], demand);
minRouteSize = atoi(argv[4]);
maxRouteSize = atoi(argv[5]);
int num_of_route_sets = atoi(argv[6]);
int numberOfNodes = dist.size();
double dw_step = 1.0 / (num_of_route_sets - 1);
for(int i=0; i<numberOfNodes; i++) popularity.push_back(0);
for(int i=0; i<numberOfNodes; i++){
for(int j=0; j<numberOfNodes; j++) popularity[i] += demand[j][i];
}
//cout << minRouteSize << endl;
//print_matrix<double>(dist);
//print_matrix<double>(demand);
for(int r = 0; r < num_of_route_sets; r++)
{
//printf("generating %d\n", r);
_RouteSet result;
double dw = r * dw_step;
getBestRouteSet(dist, demand, atoi(argv[3]), result, dw);
for(int i=0; i<result.size(); i++){
if(!checkRoute(result[i], dist, maxRouteSize, minRouteSize)) {
printf("Route is dangerous %d \n", i);
}
for(int j=0; j<result[i].size(); j++) cout << result[i][j] << ' ';
cout << "-1\n";
}
cout << "\n";
}
return 0;
}
Rik
Rik 2022 年 1 月 14 日
@Mohsen, you must be joking.
Have a read here and here. It will greatly improve your chances of getting an answer.
This answer (including your comment) will be deleted shortly.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by