0
votes

I was trying to get an vector optimized version of the linear rectifier. i.e. y = max(0,x). So what it should compute its element wise max of zero and x_i. I obviously implemented:

function [ y ] = rectSig( x )
%rectSig computes vector-wise rectified linear function
%  computes y = [..., max(0,x_i), ...]
n=length(x);
y = zeros(1,n);
for i=1:1:length(x);
    y(i) = max(0,x(i));
end
end

however, I know that looping like this in MATLAB is ill advised. So I was wondering if there was a better way to do this or if obviously matlab had its own implementation of a vectorized version of such a function? I always try to avoid loops if I can in matlab if there is a way to vectorize my code. It usually tends to speed things up.

Btw, I obviously tried googling it but didn't really get the result I expected...

2

2 Answers

2
votes

The solution is as simple as

y = max(x,0);

This works for x being a column, row vector, matrix, higher dimensional matrix, etc. On the other hand

y = max(zeros(1,length(x)),x);

only works for x being a row vector. It fails when x is a column vector or matrix.

2
votes

max accepts matrix inputs:

x = -5:5;
comparisonvector = zeros(size(x));
y = max(comparisonvector, x);

Returns:

y =

 0     0     0     0     0     0     1     2     3     4     5