开发者

element wise operation - MATLAB

开发者 https://www.devze.com 2023-04-13 02:42 出处:网络
I have a matrix in MATLAB, lets say: a = [ 897996 725174 948887 694778 ] I want to subtract from each element the avera开发者_Python百科ge of its column and divide by the column\'s standard deviati

I have a matrix in MATLAB, lets say:

a = [
  89  79  96  
  72  51  74  
  94  88  87  
  69  47  78
]

I want to subtract from each element the avera开发者_Python百科ge of its column and divide by the column's standard deviation. How can I do it in a way which could be implemented to any other matrix without using loops.

thanks


If your version supports bsxfun (which is probably the case unless you have very old matlab version), you should use it, it's much faster than repmat, and consumes much less memory. You can just do: result = bsxfun(@rdivide,bsxfun(@minus,a,mean(a)),std(a))


You can use repmat to make your average/std vector the same size as your original matrix, then use direct computation like so:

[rows, cols] = size(a); %#to get the number of rows

avgc= repmat(avg(a),[rows 1]); %# average by column, vertically replicated by number of rows
stdc= repmat(std(a),[rows 1]); %# std by column, vertically replicated by number of rows
%# Here, a, avgc and stdc are the same size
result= (a - avgc) ./ stdc;

Edit:

Judging from a mathworks blog post,bsxfun solution is faster and consumes less memory (see acai answer). For moderate size matrices, I personally prefer repmat that makes code easier to read and debug (for me).


You could also use the ZSCORE function from the Statistics Toolbox:

result = zscore(a)

In fact, it calls BSXFUN underneath, but it is careful not to divide by a zero standard deviation (you can look at the source code yourself: edit zscore)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号