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

7 vues (au cours des 30 derniers jours)
Aaron Taub
Aaron Taub le 29 Mar 2019
Commenté : Kevin Phung le 29 Mar 2019
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

Réponse acceptée

Stephan
Stephan le 29 Mar 2019
Modifié(e) : Stephan le 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 commentaire
Kevin Phung
Kevin Phung le 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)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by