Plotting y=x^n in MATLAB with Loops

  • Thread starter Thread starter fball558
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
fball558
Messages
143
Reaction score
0
anyone know MATLAB?

Homework Statement


Using Matlab, write an m-file that creates subplots of y=x^n for n=[1:6] and
x = [-10:0.01:10]. Each subplot needs appropriate labels in bold and using superscripts. this should also be commanded from within a loop and using num2str commands where necessary.



The Attempt at a Solution



i started out with a nested for loop as followed.

for x = [-10:0.01:10]
for n=[1:6]
y=x^n
plot(y) trying to just graph what I am getting so far in the loop
end
end


when i run the program i get just a blank graph??
any help would be great!
 
Physics news on Phys.org
fball558 said:

Homework Statement


Using Matlab, write an m-file that creates subplots of y=x^n for n=[1:6] and
x = [-10:0.01:10]. Each subplot needs appropriate labels in bold and using superscripts. this should also be commanded from within a loop and using num2str commands where necessary.



The Attempt at a Solution



i started out with a nested for loop as followed.
Code:
for x = [-10:0.01:10]
   for n=[1:6]
      y=x^n
      plot(y)          [b]%[/b]trying to just graph what I am getting so far in the loop
    end
end

when i run the program i get just a blank graph??
any help would be great!

Well, the beauty of MATLAB is that you can run operations on vectors and arrays, and don't have to do element-wise operations (most of the time), as you might in C or C++ (or whatever your intro computing course was).

So, you could do something like the following:
Code:
x=[0:0.01:10]
y=x.^1     %note the period before the ^, this tells MATLAB to raise each element of x to the power of 1

plot(y,x)
pause(1)     %pauses a second

y=x.^2
plot(y,x)

Now, you could pack each of your y-vectors into a 2-D matrix (array), and sort things out later, or you can use a cell array (the curly braces), and store the vectors separately.

Code:
x=[0:0.1:10];
for n=1:6
     y{n}=x+1;
end
plot(x,y{1}, x,y{2}, x,y{3}, x,y{4}, x,y{5}, x,y{6})

BTW, a great way to find what MATLAB functions do is just to type 'help' and the name of the function, for instance:
>> help plot

...which brings up the help file for the Plot function. More in-depth documentation is available at the MATLAB website (I found this invaluable when I was a MATLAB programmer one summer--bookmark the top page!):
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/arithmeticoperators.html