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

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

 채택된 답변

Stephan
Stephan 2019년 3월 29일
편집: Stephan 2019년 3월 29일
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

@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)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2019년 3월 29일

댓글:

2019년 3월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by