如何有效地在MATLAB中对向量进行归一化?任何相关的内置功能? [英] How to normalize a vector in MATLAB efficiently? Any related built-in function?

查看:153
本文介绍了如何有效地在MATLAB中对向量进行归一化?任何相关的内置功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB中将向量V归一化,如下所示:

I normalize a vector V in MATLAB as following:

normalized_V = V/norm(V);

但是,这是在MATLAB中归一化矢量的最简便(有效)方法吗?

however, is it the most elegant (efficient) way to normalize a vector in MATLAB?

推荐答案

您建议的原始代码是最好的方法.

The original code you suggest is the best way.

Matlab至少在大型矢量方面非常擅长矢量化操作.

Matlab is extremely good at vectorized operations such as this, at least for large vectors.

内置的规范功能非常快.以下是一些计时结果:

The built-in norm function is very fast. Here are some timing results:

V = rand(10000000,1);
% Run once
tic; V1=V/norm(V); toc           % result:  0.228273s
tic; V2=V/sqrt(sum(V.*V)); toc   % result:  0.325161s
tic; V1=V/norm(V); toc           % result:  0.218892s

在这里第二次计算V1只是为了确保在第一次调用时没有重要的缓存惩罚.

V1 is calculated a second time here just to make sure there are no important cache penalties on the first call.

此处的计时信息是使用Windows上的R2008a x64产生的.

Timing information here was produced with R2008a x64 on Windows.

根据gnovice的建议修订的答案(请参阅评论).矩阵数学(很少)获胜:

Revised answer based on gnovice's suggestions (see comments). Matrix math (barely) wins:

clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V);         end; toc % 6.3 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 9.3 s
tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 6.2 s ***
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 9.2 s
tic; for i=1:N, V1=V/norm(V);           end; toc % 6.4 s

恕我直言,"norm(V)"和"sqrt(V'* V)"之间的差异很小,以至于对于大多数程序而言,最好使用更清晰的程序.对我而言,范数(V)"更清晰易读,但"sqrt(V'* V)"在Matlab中仍然很常见.

IMHO, the difference between "norm(V)" and "sqrt(V'*V)" is small enough that for most programs, it's best to go with the one that's more clear. To me, "norm(V)" is clearer and easier to read, but "sqrt(V'*V)" is still idiomatic in Matlab.

这篇关于如何有效地在MATLAB中对向量进行归一化?任何相关的内置功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆