If v=-10:1:10, why isn't the v>0 case triggered?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2023년 11월 2일
편집: Walter Roberson
2023년 11월 2일
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
Walter Roberson
2023년 11월 2일
편집: Walter Roberson
2023년 11월 2일
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
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!