if statement inside of a Function is working only in certain conditions
Show older comments
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
Accepted Answer
More Answers (3)
the cyclist
on 12 Feb 2023
Edited: the cyclist
on 12 Feb 2023
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;
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])
.
I would implement the function in a bit different way:
t = -2:0.2:5;
v_c = capacitorVoltage(t);
plot(t, v_c);
xlabel('t'); ylabel('v\_c');
function x = capacitorVoltage (t)
x = 1.5+3.5*exp(-1.25.*t);
x(t<0) = 5;
end
8 Comments
Julian
on 12 Feb 2023
Askic V
on 12 Feb 2023
@Star Strider, I think the function would look like this:
capacitorVoltage = @(t) 5*(t<0) + (1.5+3.5*exp(-1.25.*(t))).*(t>=0);
Julian
on 12 Feb 2023
Askic V
on 12 Feb 2023
It is a regular multiplication, nothing more.
Julian
on 12 Feb 2023
Askic V
on 12 Feb 2023
Yes, very short and elegant solution, but you always need to be aware of potential implications when using vectors in if/else statements. This can be a source of very nasty bugs n the code.
Julian
on 12 Feb 2023
Julian
on 12 Feb 2023
Categories
Find more on Profile and Improve Performance in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
