// L2norm.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct
{
int rows;
int cols;
float* data;
}Matrix;
void inint(int rows, int cols,Matrix& matrix )
{
int j;
matrix.rows=rows;
matrix.cols=cols;
float *data=(float*)malloc(rows*cols*sizeof(float));
//if(data==NULL)coutn<<"malloc wrong !";return;
for(int i=0;i<rows;i++)
{
float* src=data+i*cols;
j =0;
while(j<cols)
{
*(src+j)=rand()%10;
j++;
}
}
matrix.data=data;
}
void L2NormRowWise(const Matrix& matrix,Matrix& temp)
{
temp.rows=matrix.rows;
temp.cols=matrix.cols;
temp .data=(float*)malloc(temp.rows*temp.cols*sizeof(float));
//计算行和
float *sumOfRow =new float[matrix.rows];
for(int i=0;i<matrix.rows;i++)
sumOfRow[i]=0;
for(int i=0;i<temp.rows;i++)
{
for(int j=0;j<temp.cols;j++)
{
sumOfRow[i]+=*(matrix.data+i*matrix.cols+j);
}
cout<<sumOfRow[i]<<endl;
for(int k=0;k<temp.cols;k++)
{
*(temp.data+i*temp.cols+k)=*(matrix.data+i*matrix.cols+k)/sumOfRow[i];
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Matrix matrix;
inint(4,10,matrix);
float*data =matrix.data;
int j;
for(int i=0;i<matrix.rows;i++)
{
float* src=data+i*matrix.cols;
j =0;
while(j<matrix.cols)
{
float temp =*(src+j);
cout<<temp<<" ";
j++;
}
cout<<endl;
}
Matrix a;
L2NormRowWise(matrix,a);
float*data1=a.data;
for(int i=0;i<a.rows;i++)
{
float* src=data1+i*a.cols;
j =0;
while(j<a.cols)
{
float temp =*(src+j);
cout<<temp<<" ";
j++;
}
cout<<endl;
}
free(data);
free(a.data);
cout<<"done!"<<endl;
return 0;
}
纯属练手
最新推荐文章于 2023-04-30 20:40:43 发布