纯属练手

本文介绍了一个使用C++实现的矩阵L2范数归一化的具体方法。通过对矩阵每一行元素求和并进行归一化处理,使得每行元素之和为1,实现了矩阵数据的标准化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值