Solving MatLab "for" Loops With Vectors

AI Thread Summary
The discussion focuses on solving a MATLAB homework problem involving the evaluation of the function y(x) = x^2 - 3x + 2 for values of x from -1 to 3 in increments of 0.1, using both a for loop and vectorization. The initial attempt with a for loop fails to produce the correct graph due to misunderstanding how MATLAB handles scalar values within the loop. The suggested solution involves using a loop index to correctly reference the elements of the x vector and plotting the results accordingly. Additionally, it is noted that vectorized operations are more efficient and should be used where possible. The final code snippets provided clarify the correct implementation for both methods.
sirclash
Messages
7
Reaction score
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 won't show the correct graph.
 
Physics news on Phys.org


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.
 


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:


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)
 

Similar threads

Back
Top