How can i run the for loop with a stepsize smaller than one?
33 views (last 30 days)
Show older comments
I have this code:
c=0:0.001:1;
volume =0.75*pi*c-pi*c.^3;
plot(c,volume)
n=4;
for i=1:4
func=@(r) -pi*r^3+0.75*pi*r;
if func(i+1)-func(i)<0 && func(i)-func(i+1)>0
a=func(i);
disp( -a )
break
else
disp('no')
end
end
I want to find the maximum volume, it is located in x=0.5 but the problem is that when i run the code the first step goes to one, which is already a negative value. I've tried: i=0:0.001:1, since that is the part where the maximum value is, but i get a totally different answer. Help would be appreciated, thank you very much.
0 Comments
Answers (2)
Walter Roberson
on 24 May 2015
Your
func=@(r) -pi*r^3+0.75*pi;
needs to be
func=@(r) -pi*r^3+0.75*pi*r;
if you want to match your plot.
2 Comments
Image Analyst
on 24 May 2015
You're not indexing the c ("x") properly. See my code below:
c=0:0.001:1;
volume =0.75*pi*c-pi*c.^3;
plot(c,volume, 'b-')
grid on;
xlabel('c', 'FontSize', 16);
ylabel('Volume', 'FontSize', 16);
n=4;
for k = 1 : length(c)
ck = c(k);
ck1 = c(k + 1);
fprintf('c(%d) = %f\n', k, ck);
func=@(r) -pi*r^3+0.75*pi*r;
if func(ck1)-func(ck)<0 && func(ck)-func(ck1)>0
a=func(ck);
fprintf('-a = %d\n', -a);
fprintf('Found peak at index %d, where c = %f\n', k, ck);
break
else
fprintf('no\n')
end
end
Just copy and paste it and try it. It works.
0 Comments
See Also
Categories
Find more on Lighting, Transparency, and Shading in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!