Matlab for loop problem

  • MATLAB
  • Thread starter kschul14
  • Start date
  • #1
2
0
I'm have a really hard time understanding for loops in matlab. How can I solve y=x^3+1 with a for loop?
 

Answers and Replies

  • #2
806
23
Why would you use a for loop? Are you implementing some sort of iterative algorithm? Just use the cubic formula.
This really belongs in the programming section. I'll ask one of the mods to move it.
 
  • #3
2
0
it's an assignment. we are supposed to use the dot operator which is really easy and a for loop and the range is 0<=x<=2 with 100 points distributed uniformly. I have tryed the fallowing
for i=0:01:2
y(i)=1+i^3
end
this won't work
 
  • #4
jhae2.718
Gold Member
1,161
20
To get a uniformly space range of numbers on a specified interval use the linspace command.

If you are trying to find the zero(s) of the function, what is a test you can use to check if you are close?

You may also find eps, the machine epsilon, to be of use.
 
  • #5
806
23
it's an assignment. we are supposed to use the dot operator which is really easy and a for loop and the range is 0<=x<=2 with 100 points distributed uniformly. I have tryed the fallowing
for i=0:01:2
y(i)=1+i^3
end
this won't work
You're trying to raise a vector to a power; using "i^3" will attempt to multiply i*i*i, which is not what you want. The correct expression is "i.^3". You should be able to figure out what to do from there.
 
  • #6
jhae2.718
Gold Member
1,161
20
Code:
[COLOR="Blue"]for[/COLOR] i=0:01:2
    y(i)=1+i^3
[COLOR="Blue"]end [/COLOR]
You are using i as an index for y, when i is not an integer. (You can't get the 0.1th element of y, for example.)

In MATLAB, you should always prefer using vectors to loops. How can you vectorize this?
 

Related Threads on Matlab for loop problem

  • Last Post
Replies
2
Views
2K
Replies
2
Views
2K
Replies
1
Views
3K
Replies
1
Views
6K
  • Last Post
Replies
3
Views
3K
  • Last Post
Replies
10
Views
16K
  • Last Post
Replies
1
Views
643
Replies
1
Views
3K
Replies
1
Views
2K
  • Last Post
Replies
3
Views
3K
Top