Solving MatLab "for" Loops With Vectors

Click For Summary
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 between -1 and 3, using both "for" loops and vectorization. The initial attempt with a "for" loop fails to produce the correct graph due to the scalar nature of x, which leads to incorrect plotting. The correct approach involves using a vector for x and iterating through its elements, allowing for proper evaluation and plotting of the function.

PREREQUISITES
  • Understanding of MatLab syntax and functions
  • Familiarity with vector operations in MatLab
  • Knowledge of plotting functions in MatLab
  • Basic understanding of polynomial functions
NEXT STEPS
  • Learn about vectorization techniques in MatLab to improve code efficiency
  • Explore MatLab's plotting functions for better data visualization
  • Study the differences between scalar and vector operations in MatLab
  • Investigate optimization strategies for loops in MatLab
USEFUL FOR

Students, educators, and professionals working with MatLab who are looking to optimize their coding practices and improve their understanding of vectorization versus iterative approaches.

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

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
Replies
2
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 32 ·
2
Replies
32
Views
5K
  • · Replies 6 ·
Replies
6
Views
2K