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

 Accepted Answer

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 Comment

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!

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

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

Start Hunting!