Why do I get an error message for below code? Output argument "C" not assigned?

The argument "C" definitely is assigned!!
function [ C ] = C_Stumpf(z)
if z > 0
C = 1;
elseif z < 0
C = -1;
elseif Z == 0
C = 0;
end
end
clear
clc
z = -50 : .1 : 500;
f = C_Stumpf(z);
plot(z,f);

 采纳的回答

You are passing a vector into the function. Your z > 0 test becomes a vector test, resulting in a vector of true and false answers. When you apply "if" to a logical vector, the result is only considered to be true if all of the entries in the logical vector are true. Since at least one if them is not, control passes to the "elseif", which has the same problem, that the condition there does not hold true for all members, so control passes to the "elseif" where again the condition there does not hold for all members. As a result, at the end of the chain, none of the conditions have held and no value has been assigned to C.

1 个评论

Wow. Thanks for the answer! I need to be more cognizant of the type of variable I'm passing. I thought I was passing a scalar into the function. I'm definitely not used to MATLAB yet. Thanks!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by