Kwa
Kwa

Reputation: 13

if statement with for loop

I am writing a function to calculate a value of p.

The formula is p=r*q + pa. The pa value is column vector which i have got from the ode45 function. I have to change the value of q w.r.t time i.e from 0 to 1 sec q=500, from 1 to 2 sec q=0.

I have written this program:

function [p] = fom(t,pa)
r=0.007;
tin=1;
t=0:0.01:2;

if t <=tin
    q = 600;
else t <= 2
    q = 0;
end

[t,pa]=ode45('FOM1',[t],[0])

for i=[palv]
    p=(r*q)+(i);
end

end

The problem is I am getting correct values after 1 sec in my output but before 1 sec where q is 0 values are not changing. Is this if statement correct?

Upvotes: 0

Views: 61

Answers (1)

hbaderts
hbaderts

Reputation: 14371

The problem is the following code snippet:

if t <=tin
    q = 600;
else t <= 2
    q = 0;
end

With t <= tin, you compare each element of vector t with tin. The result is again a vector, which contains 1 for all elements in t, which are smaller than tin, and 0 for all elements which are larger than tin, i.e.

[ 1    1    ...     1    1    0    0    ...    0 ]

According to the documentation, if evaluates the following:

An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.

As the vector contains ones and zeros, i.e. not only nonzero elements, the this always evaluates to false and the else clause will be executed. q will therefore be a scalar, not a vector, which is always 0. To get a vector q, which is 600 for all t <= tin and zero otherwise, you can use

q = 600*(t <= tin);

which creates such a vector as printed above, and multiplies it by 600.

Now, a number of comments on your code:

Regarding the else: in the else, you can't have any other conditions, so t <= 2 will just be executed and printed to the console, but this does nothing, so you can leave that away.

You have t and pa as inputs to the function, but never use them. t is simply overwritten. So either leave t an input and don't overwrite it, or leave it away as input. Further, you can remove pa as input, as you calculate it using ode45.

I assume for i = palv is a typo and should be for i = pa.

In this for loop, by calling p=(r*q)+(i);, p gets overwritten in every iteration, i.e. the resulting p will be r*q plus the last element of pa. You can create a vector p without a for loop using

p = r*q + pa

Everything together, the function becomes

function p = fom(t)

r=0.007;
tin=1;

q = 600 * (t <= tin);
[t,pa]=ode45('FOM1',[t],[0])
p = r*q + pa

end

and can be called e.g. by

t = 0:0.01:2
p = fom(t);

Upvotes: 1

Related Questions