Convert norm Matlab Function to C

When use Matlab, I have use “norm” function. I have created a simple C code to convert this norm Matlab function. Please look code below :

#include 
#include 

#define ABS(a) (((a) < (0)) ? (-a) : (a))

double norm(double *x, int nx, char *p)
{
	double xout;
	double tmp1;
	double dp;
	int btype, i;

	if (strcmp(p, "inf") == 0)
	{
		dp = 0.0;
		btype = -1;
		xout = ABS(x[0]);
	}
	else if (strcmp(p, "-inf") == 0)
	{
		dp = 0.0;
		btype = -2;
		xout = ABS(x[0]);
	}
	else if (strcmp(p, "fro") == 0)
	{
		dp = 2.0;
		btype = 1;
		xout = 0.0;
	}
	else
	{
		sscanf(p, "%lf", &dp);
		btype = 2;
		xout = 0.0;
	}

	for (i=0; i<nx; i++)
	{
		tmp1 = ABS(x[i]);
		if(btype==-1) //inf type
		{
			if (xout < tmp1) xout = tmp1; } else if(btype==-2) //-inf type { if (xout > tmp1)
				xout = tmp1;
		}
		else //double input p
			xout = xout + pow(tmp1, dp);
	}

	if(dp>0)
		xout = pow(xout, 1.0 / dp);

	return(xout);
}

int main(int argc, char **argv) 
{
	double A[] = {5, 6, 1, 5, 4, 6};
	int nA = 6; //size of vector ABS

	double b1 = norm(A, nA, "2");
	double b2 = norm(A, nA, "10");
	double b3 = norm(A, nA, "inf");
	double b4 = norm(A, nA, "fro");

	printf("norm(A,2) = %lf \n", b1);
	printf("norm(A,10) = %lf \n", b2);
	printf("norm(A,'inf') = %lf \n", b3);
	printf("norm(A,'fro') = %lf \n", b4);
	return(0);
}

Save code C norm code above with name norm.c. Please compile C norm code with command :

gcc norm.c -o norm

Below is testing C norm code result :

C:\temp>norm.exe
norm(A,2) = 11.789826
norm(A,10) = 6.532499
norm(A,'inf') = 6.000000
norm(A,'fro') = 11.789826

If you check using Matlab, you will get same result from my C Norm code.

Add a Comment

Your email address will not be published. Required fields are marked *