How to get a function to accept a vector as input?

1 view (last 30 days)
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

Accepted Answer

Stephan
Stephan on 29 Mar 2019
Edited: Stephan on 29 Mar 2019
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
  1 Comment
Kevin Phung
Kevin Phung on 29 Mar 2019
@Aaron Taub Stephan's answer will actually solve your dilemma, so I'll remove mine and would like to add a bit as to why your code didn't work:
if W is a vector, then you will have logical arrays for your if and elseif conditions.
for example, if i had:
x = 1:5
if x<3
%insert some code here
end
the inside of this if-statement would never run because it will be evaluating a logical array of
' 1 1 0 0 0'
When it is only supposed to be evaluating logical scalars (one value, either 1 or 0)

Sign in to comment.

More Answers (0)

Categories

Find more on Linear Programming and Mixed-Integer Linear Programming in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!