If v=-10:1:10, why isn't the v>0 case triggered?
1 view (last 30 days)
Show older comments
I am trying to understand if I call my function:
v=-10:0.1:10;%voltage across transistor
i = logic(v,25)
And my function is:
function i = logic(v,T)
if(v>=0)%forward
if(T==25)
i1="T=25, forward";
end
if(T==150)
i1="T=150, forward";
end
else%reverse v<0
if(T==25)
i2="T=25, backward";
end
if(T==150)
i2="T=150, backward";
end
end
i=i1+i2;
I thought i would be "T=25, backwardT=25, forward". But instead MATLAB gave me an error saying "Unrecognized function or variable 'i1'." So I think the if(v>=0) case wasn't even executed. But v=-10:1:10 contains positive values as well.
0 Comments
Accepted Answer
Walter Roberson
on 2 Nov 2023
Edited: Walter Roberson
on 2 Nov 2023
You are passing the entire vector v into logic(). Inside logic() you are testing if(v>=0) -- so you were testing the entire vector at the same time in a single if statement. But in MATLAB, if CONDITION is equivalent to if ALL(CONDITION(:)~=0) -- that is, the body of the if statement is executed only if all of the values being tested at the same time are non-zero. When the test involves a logical operator, that is equivalent to saying that the body is only executed if all of the tests on the vector came out true. But there are negative entries in the vector so testing > 0 is going to fail.
MATLAB never automatically tests each individual entry in a vector or array to somehow gather the results up. if is not a loop.
v=-10:0.1:10;%voltage across transistor
i = arrayfun(@(V)logic(V,25), v)
function i = logic(v,T)
i1 = "";
i2 = "";
if(v>=0)%forward
if(T==25)
i1="T=25, forward";
end
if(T==150)
i1="T=150, forward";
end
else%reverse v<0
if(T==25)
i2="T=25, backward";
end
if(T==150)
i2="T=150, backward";
end
end
i=i1+i2;
end
1 Comment
Walter Roberson
on 2 Nov 2023
Edited: Walter Roberson
on 2 Nov 2023
If you do not want to arrayfun to call the function repeatedly, then you need to loop inside the function.
v=-10:0.1:10;%voltage across transistor
i = logic(v,25)
function i = logic(V,T)
numv = numel(V);
i = strings(1, numv);
for K = 1 : numv
v = V(K);
i1 = compose("<no match for v=%g T=%g>", v, T);
if(v>=0)%forward
if(T==25)
i1="T=25, forward";
end
if(T==150)
i1="T=150, forward";
end
else%reverse v<0
if(T==25)
i1="T=25, backward";
end
if(T==150)
i1="T=150, backward";
end
end
i(K) = i1;
end
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!