MatLab for loops

  • Thread starter sirclash
  • Start date
  • #1
7
0
MatLab "for" loops

Homework Statement


Write an m-file to evaluate y(x)= x^2 - 3x +2 for all values of x between -1 and 3, in steps of .1 . Do this twice, once with a for loop and once with vectors. Plot the resulting functions.


Homework Equations





The Attempt at a Solution


count=0;
for x= -1:.1:3
count = count+1;
y(count)= x.^2 -3*x +2;

end
plot(x,y)

z=-1:.1:3;
u= z.^2 -3*z + 2;
plot(z,u)

My vector is correct, however i have no clue why my "for" loop wont show the correct graph.

Homework Statement





Homework Equations





The Attempt at a Solution

 

Answers and Replies

  • #2
85
1


the problem is that x is a scalar, so you're plotting (3, {y_1,y_2,...y_n}) which makes no sense.

Instead, try this: plot(-1:.1:3,y)

also, inside your for loop, you don't need ".^". You can just use "^" since x is scalar there.
 
  • #3
28
0


well, when you use the "for" part and say for x = -1:.1:3 . matlab only uses this for the loop. it does not make a vector out of it. well, i think it just keeps changing the value of x so that the value of x is the value for your last loop
try putting x = -1:.1:3 after your loop and keeping the plot(x,y)
 
Last edited:
  • #4
272
0


sirclash, here check this code. It can clean up your code and make it a lot more efficient

Code:
%plot x, y
x= -1:.1:3;

for i=1:length(x)
y(i)= x(i)^2 -3*x(i) +2;
end

plot(x,y)

%plot z, u
z=-1:.1:3;
u= z.^2 -3*z + 2; 
plot(z,u)
 

Related Threads on MatLab for loops

  • Last Post
Replies
8
Views
1K
  • Last Post
Replies
22
Views
5K
Replies
1
Views
3K
  • Last Post
Replies
0
Views
5K
Replies
10
Views
11K
  • Last Post
Replies
1
Views
1K
Replies
4
Views
1K
  • Last Post
Replies
2
Views
1K
Replies
4
Views
4K
Replies
5
Views
4K
Top