MATLAB: How to get a function to accept a vector as input

functionsMATLABvector

I'm trying to write a function that takes multiple variables in
function [x] = classproj(W, k1, k2, d)
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
if W.*(1./k1) < d
x = W.*(1/k1);
elseif W.*(1/k1) >= d
x = (W + 2*k2*d).*(1./(k1+2*k2));
end
end
This works if all variables are scalar, but if I try to make W a vector it results in an error claiming that x is not assigned during call

Best Answer

Hi,
no if-else is needed, when using logical indexing:
function [x] = classproj(W, k1, k2, d)
x(W.*(1/k1)<d) = W(W.*(1/k1)<d).*(1./k1);
x(W.*(1/k1)>=d) = (W(W.*(1/k1)>=d) + 2*k2*d).*(1./(k1+2*k2));
end
Best regards
Stephan