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

7 ビュー (過去 30 日間)
Aaron Taub
Aaron Taub 2019 年 3 月 29 日
コメント済み: Kevin Phung 2019 年 3 月 29 日
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 件のコメント
Kevin Phung
Kevin Phung 2019 年 3 月 29 日
@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 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by