cs27275
cs27275

Reputation: 69

conditional statement with for loop

Not sure what I am doing wrong here;

I am trying to make a for loop with conditional statements for the following functions. I want to make it though so h is not a vector. I am doing this for 1 through 5 with increment 0.1.

Y = f(h) = h^2    if h <= 2 or h >= 3
Y = f(h) = 45     otherwise

my code is

for h = 0:0.1:5
if h <= 2;
   Y = h^2;
elseif h >= 3;
Y = h^2;
else;
   h = 45;
end
end

Upvotes: 1

Views: 234

Answers (2)

Engineero
Engineero

Reputation: 12918

Why do you want to avoid making h an array? MATLAB specializes in operations on arrays. In fact, vectorized operations in MATLAB are generally faster than for loops, which I found counter-intuitive having started coding in C++.

An example of a vectorized verison of your code could be:

h = 0:0.1:5;
inds = find(h > 2 & h < 3);  % grab indices where Y = 45
Y = h.^2;  % set all of Y = h^2
Y(inds) = 45;  % set only those entries for h between 2 and 3 to 45

The period in the .^2 operator broadcasts that operator to every element in the h array. This means that you end up squaring each number in h individually. In general, vectorized operation like this are more efficient in MATLAB, so it is probably best to get in the habit of vectorizing your code.

Finally, you could reduce the above code a bit by not storing your indices:

h = 0:0.1:5;
Y = h.^2;  % set all of Y = h^2
Y(find(h > 2 & h < 3)) = 45;  % set only those entries for h between 2 and 3 to 45

This blog series seems to be a good primer on vectorizing your MATLAB code.

Upvotes: 2

Eli Duenisch
Eli Duenisch

Reputation: 526

This could be done easier, but with a for loop i think you could use:

h=0:0.1:5;
y=zeros(1,length(h));

for i=1:length(h)
    if or(h(i) <= 2, h(i) >= 3)
       y(i) = h(i)^2;
    else
       y(i) = 45;
    end
end

Upvotes: 3

Related Questions