将函数应用于矩阵的每一列(向量化) [英] apply function to each column of a matrix (Vectorizing)

查看:87
本文介绍了将函数应用于矩阵的每一列(向量化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在矩阵的每一列上不循环遍历的最快方法是什么?

What is fastest way of applying function on each column of a matrix without looping through it?

我正在使用的功能是pwelch,但是任何功能的概念都应该相同. 目前,我正在遍历矩阵.

The function I am using is pwelch but the concept should be the same for any function. Currently I am looping though my matrix as such.

 X = ones(5);
    for i = 1:5 % length of the number of columns
    result = somefunction(X(:,i))
    end

有矢量化此代码的方法吗?

Is there a way to vectorize this code?

推荐答案

您说

任何功能的概念应该相同

the concept should be the same for any function

实际上并非如此.根据函数的不同,调用它的代码可以进行矢量化处理,也可以不进行矢量化处理.这取决于函数的内部编写方式.从函数外部,您无法执行使其向量化的任何操作.向量化是在函数内 完成的,而不是从外部进行的.

Actually that's not the case. Depending on the function, the code that calls it can be made vectorized or not. It depends on how the function is written internally. From outside the function there's nothing you can do to make it vectorized. Vectorization is done within the function, not from the outside.

如果对函数 进行矢量化处理,则只需使用矩阵对其进行调用,并且该函数可在每一列上使用.例如,这就是sum的作用.

If the function is vectorized, you simply call it with a matrix, and the function works on each column. For example, that's what sum does.

对于pwelch,您很幸运:根据文档(添加了强调),

In the case of pwelch, you are lucky: according to the documentation (emphasis added),

Pxx = pwelch(X)返回功率谱密度(PSD)估计值,Pxx,...

Pxx = pwelch(X) returns the Power Spectral Density (PSD) estimate, Pxx, ...

X是矩阵时,PSD为 为每列独立计算并存储在相应的列中 Pxx 列.

When X is a matrix, the PSD is computed independently for each column and stored in the corresponding column of Pxx.

所以pwelch 一个矢量化函数.

So pwelch is a vectorized function.

这篇关于将函数应用于矩阵的每一列(向量化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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