if statement inside of a Function is working only in certain conditions
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi everyone, I'm expecting the function capacitorVoltage(t) to return '5' when the value of 't' is less than zero. However, as shown below it does not give the value '5'. Any help is greatly appreciated.
Edit: When trying only values where (t<=0) the function returns the expected output. However, when the range of "t" varies from negative to postive values it does not return the value '5' for values of 't' less than zero
%% V_c function defined at the end of file
t=-2:0.2:5
v_c=capacitorVoltage(t)
function[x]= capacitorVoltage (t)
mask1= t<0
mask2= t>=0;
x=1.5+3.5*exp(-1.25.*t);
if (mask1==1)
x=5;
end
end
댓글 수: 0
채택된 답변
John D'Errico
2023년 2월 12일
편집: John D'Errico
2023년 2월 12일
You don't understand how an if statement works on a vector. For example, what happens when I do this? Surely, in terms of the code you wrote, you would expect to see the vector [3 3 3 4 5] as a result?
x = 1:5;
if x < 3
x = 3;
end
x
So why did that not work? It failed, because if statements don't work that way!
An if statement is not a loop, that tests each element in the if, and depending on which of those elements satisfy the if, it applies to them. That is what I think you expect. In fact, this is a common mistake made.
The if statement, as applied to a conditional, where the result of that conditional test is a vector, only executes if ALL of those elements return true. For example, try this:
if x < 6
x = 3;
end
x
Why did that happen? What does the test here return?
x = 1:5;
x < 6
So if x is the vector 1:5, then the test is true for every elememnt. An the if statement executes. But then what did it do? Inside the if clause, it set the variable x to the number 3. The if statement does not assign only some of those elements the value 3. It turns the vector into a scalar, by assigning 3 to x.
This means the code you wrote cannot possibly work as you wish.
댓글 수: 3
John D'Errico
2023년 2월 12일
Your mistake is actually pretty common, in thinking that an if statement would work like a loop. So much so that I wonder if maybe the documentation and the tutorials should stress that an if does not work that way.
추가 답변 (3개)
the cyclist
2023년 2월 12일
편집: the cyclist
2023년 2월 12일
This statement
if (mask1==1)
checks if all elements of mask1 are equal to 1, and executes the next line once if they are. It is equivalent to
if all(mask1==1)
A vectorized way to do what you want (I think), without the if statement, is
x(mask1==1) = 5;
Star Strider
2023년 2월 12일
I would just set this up as an anonymous function —
capacitorVoltage = @(t) 5*(t<0);
t=-2:0.2:5;
v_c=capacitorVoltage(t);
Result = [t; v_c]
figure
plot(t, v_c)
grid
xlabel('t')
ylabel('v_c')
axis([-3 6 -0.1 5.1])
.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

