using for loop to solve a function

Given the following function ??(??) = 20000 * log(x) − 3x Use a for loop to compute f(x) for 1 ≤ x ≤ 20.
my solution
x = linspace(0,20,20);
for i=1:20
x2 = x;
y2 = 20000*log(x)-3*x;
plot(x2,y2,'r')
am i on the right track plot is blank

回答(1 个)

I know it is your homwork and appreciate that you have tried something.
I suggest you to do Matlab Onramp course which is interactive and fun to learn MATLAB.
Loop version:
x = linspace(0,20,20);
% ^^------ increase to get a smoother curve
y2=zeros(size(x)); % preallocate
for k=1:numel(x)
% x2 = x; ?? does nothing
y2(k) = 20000*log(x(k))-3*x(k);
% ^^^------ save y2 in each iteration
end
plot(x,y2,'r') % plot outside the loop
Matlab's way (vectorization):
x = linspace(0,20,20); % just three lines of code
y2 = 20000*log(x)-3*x;
plot(x,y2,'r')

11 个评论

thank you! and appreciate the detail explanation of what each line does
what does numel(x) mean
numel(x) gives number of elements in x ,
The best part in MATLAB is whenever you have a doubt just type
help numel % will give you detailed description of the command
doc numel
ok thanks! i also retested the code i posted early and it spat out a figure this time
so i have a while loop and a for loop do u happen to know how i can plot this for loop and while loop plot on the same graph?
use hold on after the first plot command
x = linspace(0,20,100);
j = 0;
while (j<=20)
y = x.^3-(5.*x).^2+2.^x-(10000.*x);
j = j+1;
end
f= plot(x,y,'--r')
hold on
x1 = linspace(1,20,100);
y2 = zeros(size(x1));
for k=1:numel(x1)
%x2 = x;
y2(k) = 20000*log(x1(k))-3*x1(k);
end
f = plot(x1,y2,'b')
when i plot both it looks wrong but seperately they look great" image attached"
I got two questions:
1) The original question you asked was about for loops ?
2) Why do you say it’s wrong ? Each graph represents different function.
i just thought it was wrong because when plotted on calc it looked wrong. im not sure if you saw the picture but the graph in blue looks different when graphed seperately
You didn't answer my first question.Plus I don't see any differences in the figure? not sure what do you mean by "i just thought it was wrong because when plotted on calc it looked wrong. " Did you verify the scale?
original question was for loops yes

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Graphics Performance 的更多信息

产品

版本

R2018b

提问:

2019-1-27

评论:

2019-1-28

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by